1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > java获取本机ip_java获取本机IP

java获取本机ip_java获取本机IP

时间:2023-05-13 22:15:09

相关推荐

java获取本机ip_java获取本机IP

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

import .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 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 getInetAddresses()

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

import .Inet4Address;

import .InetAddress;

import workInterface;

import java.util.Enumeration;

public class Main {

public static void main(String[] args) {

System.out.println("本机IP:" + getIpAddress());

}

public static String getIpAddress() {

try {

Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();

InetAddress ip = null;

while (allNetInterfaces.hasMoreElements()) {

NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();

if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {

continue;

} else {

Enumeration 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() 用于排除回送接口,非虚拟网卡,未在使用中的网络接口.

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。