社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
在开发聊天工具过程中,调用Java中InetAddress类的getLocalHost()方法,返回本机InetAddress对象
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
求助了一下万能的百度
看到一个大神的帖子:
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);
}
怎么没显示出来主机名,只显示了ip地址
增加一句代码输出主机名字
System.out.println(inetAddress.getHostName());
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!