一、使用java代码查询本机ip地址
public class TestInetAddress {
public static void main(String[] args) {
try {
String hostAddress = InetAddress.getLocalHost().getHostAddress();
System.out.println(hostAddress);
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
二、方式二
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
public class IPUtils {
public static String getIP() {
try {
Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
while (allNetInterfaces.hasMoreElements()) {
NetworkInterface netInterface = allNetInterfaces.nextElement();
Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
ip = addresses.nextElement();
if (ip != null && (ip instanceof Inet4Address)) {
String retIp = ip.getHostAddress();
if (!"127.0.0.1".equals(retIp)) {
return retIp;
}
}
}
}
return "";
} catch (Exception e) {
return "";
}
}
public static void main(String[] args) {
System.out.println(IPUtils.getIP());
}
}