`

获取本机的IP地址

    博客分类:
  • java
阅读更多
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地址。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics