Java获取本机ipv4/ipv6地址
😂 这篇文章最后更新于1184天前,您需要注意相关的内容是否还可用。
Java获取本机ip地址/ipv6地址,非用户请求返回的IP
try {
String hostAddress = InetAddress.getLocalHost().getHostAddress();
System.out.println("hostAddress:" + hostAddress);
String hostName = InetAddress.getLocalHost().getHostName();
System.out.println("hostName:" + hostName);
if (hostName.length() > 0) {
InetAddress[] addrs = InetAddress.getAllByName(hostName);
if (addrs.length > 0) {
for (int i = 0; i < addrs.length; i++) {
InetAddress address = addrs[i];
System.out.println("**********************");
System.out.println(address.getHostAddress());
if (address instanceof Inet6Address) {
System.out.println("true6");
} else if(address instanceof Inet4Address){
System.out.println("true4");
} else {
System.out.println("unknown");
}
System.out.println("**********************");
}
}
}
} catch (UnknownHostException e) {
e.printStackTrace();
}
或者
Enumeration<NetworkInterface> interfs = NetworkInterface.getNetworkInterfaces();
while (interfs.hasMoreElements()) {
NetworkInterface interf = interfs.nextElement();
Enumeration<InetAddress> addres = interf.getInetAddresses();
while (addres.hasMoreElements()) {
InetAddress in = addres.nextElement();
if (in instanceof Inet4Address) {
System.out.println("v4:" + in.getHostAddress());
} else if (in instanceof Inet6Address) {
System.out.println("v6:" + in.getHostAddress());
}
}
}
留言评论
暂无留言