先明確了解一些規則:
127.xxx.xxx.xxx 屬於”loopback” 地址,即只能你自己的本機可見,就是本機地址,比較常見的有127.0.0.1;
192.168.xxx.xxx 屬於private 私有地址(site local address),屬於本地組織內部訪問,只能在本地局域網可見。
同樣10.xxx.xxx.xxx、從172.16.xxx.xxx 到 172.31.xxx.xxx都是私有地址,也是屬於組織內部訪問;
169.254.xxx.xxx 屬於連接本地地址(link local IP),在單獨網段可用
從224.xxx.xxx.xxx 到 239.xxx.xxx.xxx 屬於組播地址
比較特殊的255.255.255.255 屬於廣播地址
除此之外的地址就是點對點的可用的公開IPv4地址
本機實際IP位置的正確方式,可以參考以下,測試得到路由所配發的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 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
package ipTest; import java.net.Inet4Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Enumeration; public class Test { public static void main(String[] args) { // TODO Auto-generated method stub InetAddress ip; try { // 正确的IP拿法 System.out.println("get LocalHost LAN Address : " + getLocalHostLANAddress().getHostAddress()); } catch (UnknownHostException e) { e.printStackTrace(); } } // 正确的IP拿法,即优先拿site-local地址 private static InetAddress getLocalHostLANAddress() throws UnknownHostException { try { InetAddress candidateAddress = null; // 遍历所有的网络接口 for (Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements();) { NetworkInterface iface = (NetworkInterface) ifaces.nextElement(); // 在所有的接口下再遍历IP for (Enumeration inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements();) { InetAddress inetAddr = (InetAddress) inetAddrs.nextElement(); if (!inetAddr.isLoopbackAddress()) {// 排除loopback类型地址 if (inetAddr.isSiteLocalAddress()) { // 如果是site-local地址,就是它了 return inetAddr; } else if (candidateAddress == null) { // site-local类型的地址未被发现,先记录候选地址 candidateAddress = inetAddr; } } } } if (candidateAddress != null) { return candidateAddress; } // 如果没有发现 non-loopback地址.只能用最次选的方案 InetAddress jdkSuppliedAddress = InetAddress.getLocalHost(); if (jdkSuppliedAddress == null) { throw new UnknownHostException("The JDK InetAddress.getLocalHost() method unexpectedly returned null."); } return jdkSuppliedAddress; } catch (Exception e) { UnknownHostException unknownHostException = new UnknownHostException( "Failed to determine LAN address: " + e); unknownHostException.initCause(e); throw unknownHostException; } } } |
Reference
https://www.cnblogs.com/starcrm/p/7071227.html