两种方法:第一种代码量比较少,但是不支持linux系统。第二种支持linux系统,但是代码量比较大。实际用的时候自己根据需要选择吧。现在将代码分别贴出来供大家参考。
第一种:
inet = InetAddress.getLocalHost();
String ipStrs = inet.getHostAddress();
System.out.println(ipStrs);
第二种:
Enumeration allNetInterfaces;
try {
allNetInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
while (allNetInterfaces.hasMoreElements())
{
NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
System.out.println(netInterface.getName());
Enumeration addresses = netInterface.getInetAddresses();
while (addresses.hasMoreElements())
{
ip = (InetAddress) addresses.nextElement();
if (ip != null && ip instanceof Inet4Address)
{
System.out.println("本机的IP = " + ip.getHostAddress());
}
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}