Home > 系统管理, 零敲碎打 > [Linux]Java获取本机网卡IP地址

[Linux]Java获取本机网卡IP地址

应用程序服务器由Windows环境整体迁移到Linux环境,出现了不能获取本机IP地址的问题
原因是下面一段JAVA代码在Linux下直接返回127.0.0.1。Windows下有效的InetAddress貌似在linux下不起作用。

1
2
3
4
5
6
7
8
9
10
11
12
public static String getLocalIP() {
    String ip = "";
        try {
            InetAddress address = InetAddress.getLocalHost();
            if(address != null) {
                ip = address.getHostAddress();
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    return ip;
}

原因在于Java使用的JNI代码调用的是Linux中的gethostname内核函数
这个函数在Linux主机没有绑定IP的情况下根据Host文件定义返回默认的localhost或者127.0.0.1。

后改为改用NetworkInterface方式获取,可以取得IP地址。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public static String getLocalIP() {
    Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();
    InetAddress ip = null;
    while (allNetInterfaces.hasMoreElements()) {
        NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
        System.out.println(netInterface.getName());
        Enumeration addresses = netInterface.getInetAddresses();
        while (addresses.hasMoreElements()) {
            ip = (InetAddress) addresses.nextElement();
                if (ip != null && ip instanceof Inet4Address) {
                    return ip.getHostAddress();
                }
            }
        }
    }
    return "";
}

最后考虑到多块网卡问题,需要对多个NetworkInterface进行遍历,这里只取IPV4的IP地址

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public static List<String> getLocalIPList() {
        List<String> ipList = new ArrayList<String>();
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            NetworkInterface networkInterface;
            Enumeration<InetAddress> inetAddresses;
            InetAddress inetAddress;
            String ip;
            while (networkInterfaces.hasMoreElements()) {
                networkInterface = networkInterfaces.nextElement();
                inetAddresses = networkInterface.getInetAddresses();
                while (inetAddresses.hasMoreElements()) {
                    inetAddress = inetAddresses.nextElement();
                    if (inetAddress != null && inetAddress instanceof Inet4Address) { // IPV4
                        ip = inetAddress.getHostAddress();
                        ipList.add(ip);
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return ipList;
    }

参考
http://www.linuxidc.com/Linux/2012-12/75498.htm
https://my.oschina.net/zhongwenhao/blog/307879
http://www.blogjava.net/icewee/archive/2013/07/19/401739.html

Categories: 系统管理, 零敲碎打 Tags: , ,
  1. No comments yet.
  1. No trackbacks yet.