验证ip地址

时间:2023-12-23 11:33:56
package site.wangxin520.test;

import sun.net.util.IPAddressUtil;

public class Test {

    public static void main(String[] args) throws Exception {
// String ip = "192.168.110.250";
// String ip = "11100100.00000100.00000101.11111101";
// String ip = "CDCD:910A:2222:5498:8475:1111:3900:2020";
// String ip = "1030::C9B4:FF12:48AA:1A2B";
String ip = "0000:0000:0000:0000:0000:0000:c0a8:5909";
// ipv6兼容ipv4方法已被舍弃,不采用下面的方式
// String ip="::192.168.89.9";
try {
if (ip.contains(".")) {
// ipv4的处理方式
if (ip.length() == 35 && ip.contains(".")) {
String[] split = ip.split("[.]");
StringBuilder sb = new StringBuilder();
for (String string : split) {
int parseInt = Integer.parseInt(string, 2);
sb.append(parseInt).append(".");
}
ip = sb.toString().substring(0, sb.toString().lastIndexOf("."));
}
System.out.println(IPAddressUtil.isIPv4LiteralAddress(ip) ? "是ipv4的IP地址" : "不是IP地址");
} else if (ip.contains(":")) {
//ipv6的处理方式
System.out.println(IPAddressUtil.isIPv6LiteralAddress(ip) ? "是ipv6的IP地址" : "不是IP地址");
} else {
System.out.println("不是ip地址");
}
} catch (Exception e) {
System.out.println("不是ip地址");
} }
}