Java获取本机IP地址
深色风信子 人气:01 获取局域网IP地址
InetAddress.getLocalHost().getHostAddress();
2 获取全部 IPV4/IPV6 IP地址
private static List<String> getIpAddress() throws SocketException { List<String> list = new LinkedList<>(); Enumeration enumeration = NetworkInterface.getNetworkInterfaces(); while (enumeration.hasMoreElements()) { NetworkInterface network = (NetworkInterface) enumeration.nextElement(); if (network.isVirtual() || !network.isUp()) { continue; } else { Enumeration addresses = network.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress address = (InetAddress) addresses.nextElement(); if (address != null && (address instanceof Inet4Address || address instanceof Inet6Address)) { list.add(address.getHostAddress()); } } } } return list; }
3 获取全部存放本机IP地址
private static List<String> getIpAddress() throws SocketException { List<String> list = new LinkedList<>(); Enumeration enumeration = NetworkInterface.getNetworkInterfaces(); while (enumeration.hasMoreElements()) { NetworkInterface network = (NetworkInterface) enumeration.nextElement(); Enumeration addresses = network.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress address = (InetAddress) addresses.nextElement(); if (address != null && (address instanceof Inet4Address || address instanceof Inet6Address)) { list.add(address.getHostAddress()); } } } return list; }
知识点补充
IP地址(Internet Protocol Address)是指互联网协议地址,又译为网际协议地址。
IP地址是IP协议提供的一种统一的地址格式,它为互联网上的每一个网络和每一台主机分配一个逻辑地址,以此来屏蔽物理地址的差异。
IP地址是一个32位的二进制数,通常被分割为4个“8位二进制数”(也就是4个字节)。IP地址通常用“点分十进制”表示成(a.b.c.d)的形式,其中,a,b,c,d都是0~255之间的十进制整数。例:点分十进IP地址(100.4.5.6),实际上是32位二进制数(01100100.00000100.00000101.00000110)。
加载全部内容