ref:https://blog.csdn.net/nianbingsihan/article/details/80265029
在Linux 和 win 下 通用的 获取IP等网络信息,就用如下方式:
NetworkInterface可以通过getNetworkInterfaces方法来枚举本机所有的网络接口。
我们也可以利用getNetworkInterfaces得到的网络接口,来枚举与每一个网络接口 绑定的所有IP地址。
getInetAddresses方法
NetworkInterface 类可以通过getInetAddresse 方法以InetAddress 对象的形式返回和网络接口绑定的所有IP 地址。getInetAddresses 方法的定义如下:
public Enumeration<InetAddress> getInetAddresses()
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
/**
* @author liangqi
* @date 2021/6/29 0:11
*/
public class NetDemo {
public static void main(String[] args) throws Exception {
System.out.println("本机IP:" + getIpAddress());
}
public static String getIpAddress() {
String hostname = "eth0";
try {
//获取所有的网络接口
Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
while (allNetInterfaces.hasMoreElements()) {
//遍历每一个网络接口
NetworkInterface netInterface = allNetInterfaces.nextElement();
//若是网路接口是:1回环接口 2虚拟网口 3网口状态为unUser,则跳过
if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {
continue;
} else {
//返回和网络接口绑定的所有ip地址
Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
String name = netInterface.getName();
System.out.println("网口名称:" + name);
while (addresses.hasMoreElements()) {
//遍历获取每一个IP地址
InetAddress inetAddress = addresses.nextElement();
System.out.println("inetAddress.getHostAddress(): " + inetAddress.getHostAddress());
if (inetAddress != null && inetAddress instanceof Inet4Address) {
return inetAddress.getHostAddress();
}
}
}
}
} catch (Exception e) {
System.err.println("IP地址获取失败" + e.toString());
}
return "";
}
}
如果是在windows环境: 使用InetAddress.getLocalHost()方法即可…在linux下 下面的获取IP的方式有时候会不准确。想要准确使用上面方式。
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