简体   繁体   中英

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.

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

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

Replace the number at the end of the input.

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

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[3] = new IPv4AddressSegment(100);
    return new IPv4Address(segs);
}

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

Output:

192.168.1.100

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM