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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值