在Windows环境获取IP用InetAddress,Linux下及Java获取IP的其他方式
如果在Windows环境中:使用InetAddress.getLocalHost()方法。

import java.net.InetAddress;
public class Main {
public static void main(String[] args)
throws Exception {
InetAddress addr = InetAddress.getLocalHost();
System.out.println("Local HostAddress:
"+addr.getHostAddress());
String hostname = addr.getHostName();
System.out.println("Local host name: "+hostname);
}
}
代码运行结果:
Local HostAddress: 192.168.42.2
Local host name: f19ca2b695da
在Linux下,上述获取IP的方法有时获得127.0.0.1。
从JDK1.4开始,Java提供了一个NetworkInterface类。此类可以使用该计算机的物理网络接口创建的逻辑网络接口的信息从该计算机的所有物理网络接口和虚拟机中获取信息。 NetworkInterface可以通过getNetworkInterfaces方法枚举机器的所有网络接口。我们还可以使用GetNetworkInterfaces获得的网络接口来枚举机器的所有IP地址。当然,您还可以通过Inetaddddddress类中的GetallByName获取机器的所有IP地址::
public static Enumeration getNetworkInterfaces() throws SocketException
但是,可以根据网络接口包装GetNetworkInterfaces方法,这对于网络接口上的所有IP地址非常有用。 NetworkInterface类提供了三种方法来获取网络接口名称(getName方法),网络接口别名(getDisPlayName方法)和所有IP地址(getInetAddresses方法)与网络接口结合:
1. getName方法
此方法用于获取网络接口的名称。此名称是使用GetByName方法创建网络接口(例如ETH0和PPP0)时使用的网络接口名称。 getName方法的定义如下:
public String getName()
2.GETDISPLAYNAME方法
此方法可以使网络接口名称更容易理解,或者此网络接口的名称也是网络接口名称。在某些操作系统(例如UNIX)中,getDisplayName方法与getName方法的返回值相同,但是Windows中的GetDisplayName方法通常返回更友好的名称,例如Arettek RTL8139 family PCI PCI PCI PCI PCI fast Ethernet NIC NIC ESSENCE nic sensence定义定义getDisplayName方法的内容如下:
public String getDisplayName()
3. getIneTaddresses方法
NetworkInterface类可以通过getInetAddresse方法返回通过felmaddress对象绑定的所有IP地址绑定和网络接口。 GetInetAddresses方法的定义如下:
public Enumeration getInetAddresses()
这是在Windows和Linux下获取IP通用采集IP的方法:
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
public class Main {
public static void main(String[] args) {
System.out.println("本机IP:" + getIpAddress());
}
public static String getIpAddress() {
try {
Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
while (allNetInterfaces.hasMoreElements()) {
NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {
continue;
} else {
Enumeration addresses = netInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
ip = addresses.nextElement();
if (ip != null && ip instanceof Inet4Address) {
return ip.getHostAddress();
}
}
}
}
} catch (Exception e) {
System.err.println("IP地址获取失败" + e.toString());
}
return "";
}
}
指示网络接口,非返回界面和非虚拟网络卡的筛选,并正在使用
笔记:
NetInterface.isloopback()|| NetInterface.isvirtual()||! NetInterface.isup()用于消除返回接口,非虚拟网络卡,而不是在使用的网络接口中。
参考本文: