
如何获取机器的ip java
用户关注问题
我需要在Java程序中获取当前运行机器的IP地址,应该如何实现?
使用InetAddress类获取IP地址
可以使用Java的InetAddress类来获取本机的IP地址。通过调用InetAddress.getLocalHost()方法,并使用getHostAddress()方法可以获得本机的IP字符串。例如:InetAddress localHost = InetAddress.getLocalHost(); String ip = localHost.getHostAddress();
如果机器有多个网卡,如何在Java中获取所有网络接口对应的IP地址?
利用NetworkInterface类遍历所有网卡
Java提供了NetworkInterface类,可以用它遍历机器上的所有网络接口并获取每个接口的IP地址。代码示例:Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface ni = interfaces.nextElement(); Enumeration addresses = ni.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress addr = addresses.nextElement(); if (!addr.isLoopbackAddress()) { System.out.println(addr.getHostAddress()); } } }
在Java获取的IP地址中,怎样判断是IPv4地址还是IPv6地址?
通过InetAddress的类型判断IP协议版本
InetAddress类有两个子类Inet4Address和Inet6Address,通过instanceof操作符可以判断具体的类型来区分IP版本。例如:if (inetAddress instanceof Inet4Address) 表示IPv4地址,如果是Inet6Address则表示IPv6地址。