Java多网卡InetAddress遇到的问题
0x00前言
在开发聊天工具过程中,调用Java中InetAddress类的getLocalHost()方法,返回本机InetAddress对象
0x01遇到的错误
先帖代码
import java.io.IOException;
import java.net.InetAddress;
public class Test {
public static void main(String[] args) throws IOException {
InetAddress inetAddress=InetAddress.getLocalHost();
System.out.println(inetAddress);
}
}
运行结果
这个并不是我想要的结果呀,然后查看了一下自己的ip地址
发现他获取的是虚拟机的一块虚拟网卡
然后查了一遍API,并没有找到我想要的192.168.43.74
0x02解决办法
求助了一下万能的百度
看到一个大神的帖子:
java获取本地IP地址,java获取本地多张网卡IPhttps://blog.csdn.net/luckly_p/article/details/47274531
发现还不是我想要的(你到底想要啥!!)
编写方法
/**
* 多网卡指定名字类型返回指定InetAddress
* 输入类型错误则输出全部网卡接口信息
*
* @param Name 名字
* @param type 类型: 4--Inet4Address 6--Inet6Address
* @return
*/
public static InetAddress getInetAddress(String Name, int type) {
try {
Enumeration<NetworkInterface> nifs = NetworkInterface.getNetworkInterfaces();
InetAddress addr;
if (type == 4) {
while (nifs.hasMoreElements()) {
NetworkInterface nif = nifs.nextElement();
Enumeration<InetAddress> addresses = nif.getInetAddresses();
while (addresses.hasMoreElements()) {
addr = addresses.nextElement();
if (nif.getName().equals(Name) && addr instanceof Inet4Address) {
return addr;
}
}
}
} else if (type == 6) {
while (nifs.hasMoreElements()) {
NetworkInterface nif = nifs.nextElement();
Enumeration<InetAddress> addresses = nif.getInetAddresses();
while (addresses.hasMoreElements()) {
addr = addresses.nextElement();
if (nif.getName().equals(Name) && addr instanceof Inet6Address) {
return addr;
}
}
}
} else {
System.out.println("类型指定错误,将输出全部网卡接口信息");
System.out.println();
while (nifs.hasMoreElements()) {
NetworkInterface nif = nifs.nextElement();
Enumeration<InetAddress> addresses = nif.getInetAddresses();
while (addresses.hasMoreElements()) {
addr = addresses.nextElement();
System.out.println("网卡接口名称:" + nif.getName());
System.out.println("网卡接口地址:" + addr.getHostAddress());
System.out.println();
}
}
return null;
}
} catch (Exception e) {
System.out.println("获取Socket失败");
}
return null;
}
调用函数
public static void main(String[] args) throws IOException {
InetAddress inetAddress=getInetAddress("wlan0", 4);
System.out.println(inetAddress);
}
编译运行
不是很完美的完美解决
0x03不足之处
怎么没显示出来主机名,只显示了ip地址
代码测试
增加一句代码输出主机名字
System.out.println(inetAddress.getHostName());
运行结果
0x04总结
- 解决的并不是很完美,希望大神能提出改善意见
- 万能的百度还是能解决很多问题的