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.

0

4 Answers 4

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
Sign up to request clarification or add additional context in comments.

Comments

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;
}

Comments

0

Replace the number at the end of the input.

String ipAddress = "192.168.1.97";
String newIpAddress = ipAddress.replaceFirst("\\d+$", "100")

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.