java获取本机IP

如果是在windows环境: 使用InetAddress.getLocalHost()方法即可.

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

在linux下上述获取IP的方式有时候会得到127.0.0.1.

从JDK1.4开始,Java提供了一个NetworkInterface类。这个类可以得到本机所有的物理网络接口和虚拟机等软件利用本机的物理网络接口创建的逻辑网络接口的信息,NetworkInterface可以通过getNetworkInterfaces方法来枚举本机所有的网络接口。我们也可以利用getNetworkInterfaces得到的网络接口来枚举本机的所有IP地址。当然,也可以通过InetAddress类的getAllByName来得到本机的所有IP地址:

public static Enumeration<NetworkInterface> getNetworkInterfaces() throws SocketException

但getNetworkInterfaces方法可以按网络接口将这些IP地址进行分组,这对于只想得到某个网络接口上的所有IP地址是非常有用的。NetworkInterface类提供了三个方法可以分别得到网络接口名(getName方法)、网络接口别名(getDisplayName方法)以及和网络接口绑定的所有IP地址(getInetAddresses方法):

1. getName方法
这个方法用来得到一个网络接口的名称。这个名称就是使用getByName方法创建NetworkInterface对象时使用的网络接口名,如eth0、ppp0等。getName方法的定义如下:

public String getName()
3. getInetAddresses方法
NetworkInterface类可以通过getInetAddresse方法以InetAddress对象的形式返回和网络接口绑定的所有IP地址。getInetAddresses方法的定义如下:
public Enumeration<InetAddress> getInetAddresses()

下面给出windows和linux下通用的获取本机IP的方法:

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
 
 
public class Main {
 
	public static void main(String[] args) {
		System.out.println("本机IP:" + getIpAddress());
	}
	
	public static String getIpAddress() {
	    try {
	      Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
	      InetAddress ip = null;
	      while (allNetInterfaces.hasMoreElements()) {
	        NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
	        if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {
	          continue;
	        } else {
	          Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
	          while (addresses.hasMoreElements()) {
	            ip = addresses.nextElement();
	            if (ip != null && ip instanceof Inet4Address) {
	              return ip.getHostAddress();
	            }
	          }
	        }
	      }
	    } catch (Exception e) {
	    	System.err.println("IP地址获取失败" + e.toString());
	    }
	    return "";
	  }
 
}

表示对网络接口进行筛选,非回送接口 且 非虚拟网卡 且 正在使用中

注:

netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp() 用于排除回送接口,非虚拟网卡,未在使用中的网络接口.

posted @ 2020-05-08 13:45  a-du  阅读(375)  评论(0编辑  收藏  举报