方法一(只能在Windows上使用):
try
{
System.out.println("本机的IP = " + InetAddress.getLocalHost());
} catch (UnknownHostException e)
{
e.printStackTrace();
}
方法二(可以在Linux下执行)
Enumeration 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());
}
}
}