import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
public class PrintLocalIpTest {
public static void main(String[] args) {
try {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
// 只看使用中的
if (!networkInterface.isUp()) {
continue;
}
System.out.println("getIndex: " + networkInterface.getIndex());
System.out.println("getDisplayName: " + networkInterface.getDisplayName());
System.out.println("getName: " + networkInterface.getName());
System.out.println("isLoopback: " + networkInterface.isLoopback());
System.out.println("isUp: " + networkInterface.isUp());
System.out.println("isVirtual: " + networkInterface.isVirtual());
System.out.println("isPointToPoint: " + networkInterface.isPointToPoint());
Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
while (inetAddresses.hasMoreElements()) {
InetAddress inetAddress = inetAddresses.nextElement();
// 只看 ipv4 地址
if (inetAddress instanceof Inet4Address) {
System.out.println("getHostAddress: " + inetAddress.getHostAddress());
System.out.println("getHostName: " + inetAddress.getHostName());
}
}
System.out.println("-----");
}
} catch (SocketException e) {
e.printStackTrace();
}
}
}
Java获取本地IP和主机名称
最新推荐文章于 2024-05-14 17:07:42 发布