问题
用Java获取本机IP地址,需要处理:
1. 多块网卡。
2. 排除loopback设备、虚拟网卡
看似简单的代码,写起来还是要小心一些的。
方案
HBase客户端获取本机IP的代码提供了一个很好的参考。没有特殊需求的话,拷贝过去用吧:)
//From HBase Addressing.Java private static InetAddress getIpAddress(AddressSelectionCondition condition) throwsSocketException { //Before we connect somewhere, we cannot be sure about what we'd be bound to; however, //we only connect when the message where client ID is, is long constructed. Thus, //just use whichever IP address we can find. Enumeration<NetworkInterface> interfaces =NetworkInterface.getNetworkInterfaces(); while(interfaces.hasMoreElements()) { NetworkInterface current =interfaces.nextElement(); if (!current.isUp() || current.isLoopback() || current.isVirtual()) continue; Enumeration<InetAddress> addresses =current.getInetAddresses(); while(addresses.hasMoreElements()) { InetAddress addr =addresses.nextElement(); if (addr.isLoopbackAddress()) continue; if(condition.isAcceptableAddress(addr)) { returnaddr; } } } throw new SocketException("Can't get our ip address, interfaces are: " +interfaces); }