JAVA应用获取本机IP

在应用开发的时候如何获取本机的IP呢?

本人在开发一个线上系统的时候有这样的需求,办法很简单啊,google一下,于是乎有了下面的代码:

方案一:

Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            if (interfaces != null) {
                while (interfaces.hasMoreElements()) {
                    try {
                        NetworkInterface network = interfaces.nextElement();
                        if ("eth0".equals(network.getName())) { // 验证只有eth0才会获取ip
                            Enumeration<InetAddress> addresses = network.getInetAddresses();
                            if (addresses != null) {
                                while (addresses.hasMoreElements()) {
                                    try {
                                        InetAddress address = addresses.nextElement();
                                        if (isValidAddress(address)) {
                                            return address;
                                        }
                                    } catch (Throwable e) {
                                        if (LOGGER.isWarnEnabled()) {
                                            LOGGER.warn("[getLocalAddress0] Failed to retriving ip address, " + e.getMessage(), e);
                                        }
                                    }
                                }
                            }
                        }
                    } catch (Throwable e) {
                        if (LOGGER.isWarnEnabled()) {
                            LOGGER.warn("[getLocalAddress0] Failed to retriving ip address, " + e.getMessage(), e);
                        }
                    }
                }
            }

这段代码中为什么加入判断eth0呢?因为一般线上服务器可能不止有一个网卡,我们线上内网都是用的eth0,所以就可以写死。但是这样毕竟不好。那怎么解决呢?

方案二:

已知线上某台服务器ip,并可以连上。通过socket链接,获取本机对内网ip

 1 private static InetAddress getLocalHostBySocket(InetSocketAddress remoteAddress) {
 2     InetAddress host = null;
 3     try {
 4         // 连远程地址
 5         Socket socket = new Socket();
 6         try {
 7             socket.connect(remoteAddress, 1000);
 8             // 得到本地地址
 9             host = socket.getLocalAddress();
10         } finally {
11             try {
12                 socket.close();
13             } catch (Throwable e) {
14             }
15         }
16     } catch (Exception e) {
17         logger.warn("Can not connect to host {}, cause by :{}",
18                 remoteAddress.toString(), e.getMessage());
19     }
20     return host;}

 

posted @ 2015-01-19 22:53  马路牙子  阅读(897)  评论(0编辑  收藏  举报