欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

获取本机的IP地址

程序员文章站 2024-01-31 16:09:52
...
1. 遍历网络接口来获取IP地址:

Enumeration<NetworkInterface> itfList = NetworkInterface.getNetworkInterfaces();
if (itfList == null) {
    System.out.println("--No interfaces found--");
} else {
    while (itfList.hasMoreElements()) {
        NetworkInterface itf = itfList.nextElement();
        String displayName = itf.getDisplayName();
        String name = itf.getName();
        if (name.indexOf("eth") < 0 && displayName.indexOf("Wireless") < 0) { // 只获取以太网卡或者无线网卡的IP,根据需要配置。
            continue;
        }
        System.out.println("Interface " + itf.getName() + ":");
        Enumeration<InetAddress> addrList = itf.getInetAddresses();
        if (!addrList.hasMoreElements()) {
            System.out.println("\t(No addresses for this interface)");
        }
        while (addrList.hasMoreElements()) {
            InetAddress addr = addrList.nextElement();
            System.out.print("\tAddress "
                + (addr instanceof Inet4Address ? "(v4)" : (addr instanceof Inet6Address ? "(v6)"
                        : "(?)")));
            System.out.println(": " + addr.getHostAddress());
        }
    }
}


2. 通过主机名来获取IP地址:

public static void getIPByHostName(String host) {
    System.out.println(host + ":");
    InetAddress[] addrList = InetAddress.getAllByName(host);
    for (InetAddress addr : addrList) {
        System.out.println("\t" + addr.getHostName() + "/" + addr.getHostAddress());
    }
}


3. 通过InetAddress来获取本机IP地址:

InetAddress address = InetAddress.getLocalHost();
System.out.println(address);


如果本机有多个网络:如以太网,无线网卡或虚拟机等,通过上面两种方式获取的可能不是需要的IP地址。
相关标签: java net