0

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.

Edward A.
  • 55
  • 6

4 Answers4

1
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
Luca Negrini
  • 490
  • 4
  • 11
0

You can use these methods

public static byte getLastOctet(String ip) {
    String octet = ip.substring (ip.lastIndexOf('.') + 1);
    return Byte.parseByte(octet);
}

public static String setLastOctet(String ip, byte octet) {
    return ip.substring(0, ip.lastIndexOf ('.') + 1) + octet;
}
Leo Aso
  • 11,898
  • 3
  • 25
  • 46
0

Replace the number at the end of the input.

String ipAddress = "192.168.1.97";
String newIpAddress = ipAddress.replaceFirst("\\d+$", "100")
Luciano van der Veekens
  • 6,307
  • 4
  • 26
  • 30
0

You can do this with the IPAddress Java library as follows. Doing it this way validates the input string and octet value. Disclaimer: I am the project manager.

static IPv4Address change(String str, int lastOctet) {
    IPv4Address addr = new IPAddressString(str).getAddress().toIPv4();
    IPv4AddressSegment segs[] = addr.getSegments();
    segs[segs.length - 1] = new IPv4AddressSegment(lastOctet);
    return new IPv4Address(segs);
}

IPv4Address next = change("192.168.1.97", 100);
System.out.println(next);

Output:

192.168.1.100
Sean F
  • 4,344
  • 16
  • 30