Java 如何修改以字符串形式输入的 IP 地址

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

我有一个程序需要提供一个 LAN IP,然后我需要能够修改 IP 的最后一个八位字节,前 3 个将根据在 LAN IP 文本中输入的内容保持不变字段.

例如: 用户输入 192.168.1.97 作为 LAN IP 我需要能够操纵最后一个八位字节“97”,我将如何去做,这样我就可以有另一个变量或字符串来表示 192.168.1.100 或我想要的任何其他内容设置在最后一个八位位组。

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

然后,如果您想将最后一个八位字节设置为 100,只需执行以下操作:

String newIp = firstThreeOctet + ".100"; // 192.168.1.100

你可以使用这些方法

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

替换输入末尾的数字。

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