Skip to content
Advertisement

Java how to Modify IP Address that was input as a string

I have a program that will take a LAN IP provided, I then need to be able to modify just the last octet of the IP’s, the first 3 will remain the same based on what was input in the LAN IP Text Field.

For example: User enter 192.168.1.97 as the LAN IP I need to be able to manipulate the last octet “97”, how would I go about doing that so I can have another variable or string that would have say 192.168.1.100 or whatever else i want to set in the last octet.

Advertisement

Answer

String ip = "192.168.1.97";

// cut the last octet from ip (if you want to keep the . at the end, add 1 to the second parameter
String firstThreeOctets = ip.substring(0, ip.lastIndexOf(".")); // 192.168.1

String lastOctet = ip.substring(ip.lastIndexOf(".") + 1); // 97

Then, if you want to set the last octet to 100, simply do:

String newIp = firstThreeOctet + ".100"; // 192.168.1.100
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement