在window下面可用如下代码:
- InetAddress inet = InetAddress.getLocalHost();
- System.out.println("本机的ip=" + inet.getHostAddress());
而在Linux下返回127.0.0.1。主要是在linux下返回的是/etc/hosts中配置的localhost的ip地址,而不是网卡的绑定地址。后来改用网卡的绑定地址,可以取到本机的ip地址:)
代码如下:
// 根据网卡取本机配置的IP
Enumeration<NetworkInterface> netInterfaces = null;
try {
netInterfaces = NetworkInterface.getNetworkInterfaces();
while (netInterfaces.hasMoreElements()) {
NetworkInterface ni = netInterfaces.nextElement();
System.out.println("DisplayName:" + ni.getDisplayName());
System.out.println("Name:" + ni.getName());
Enumeration<InetAddress> ips = ni.getInetAddresses();
while (ips.hasMoreElements()) {
System.out.println("IP:" + ips.nextElement().getHostAddress());
}
}
} catch (Exception e) {
e.printStackTrace();
}
本文介绍了一种在Java中获取本地IP地址的方法。针对Windows和Linux系统的特点,分别提供了不同的实现方式。在Windows环境下,通过InetAddress类的getLocalHost()方法即可直接获取;而在Linux系统中,则需要遍历所有网卡接口,以获取实际的IP地址。
346

被折叠的 条评论
为什么被折叠?



