gpt4 book ai didi

java - 如何使用JAVA获取局域网IP地址

转载 作者:行者123 更新时间:2023-12-01 12:16:14 26 4
gpt4 key购买 nike

我想获取连接到 LAN 的笔记本电脑的 IP 地址。这个地址必须从JAVA获取。

为此,我有以下代码来获取所有 IP 地址的列表。

try
{
Enumeration e = NetworkInterface.getNetworkInterfaces();
while(e.hasMoreElements())
{
NetworkInterface n = (NetworkInterface) e.nextElement();
Enumeration ee = n.getInetAddresses();
while (ee.hasMoreElements())
{
InetAddress i = (InetAddress) ee.nextElement();
String address;
address = i.getHostAddress();
System.out.println(i.getHostAddress());
}
}
}
catch( SocketException SE)
{
SE.printStackTrace();
}

现在我得到了以下 IP 地址列表。

127.0.0.1
0:0:0:0:0:0:0:1
192.168.10.99
fe80:0:0:0:4c55:cf87:67a0:2%10
192.168.115.215
fe80:0:0:0:a972:d8d9:c94c:4263%11
fe80:0:0:0:707c:b434:bf95:4940%12
192.168.15.1
fe80:0:0:0:1d59:66f7:e68e:31d%15 is reachable
fe80:0:0:0:1d59:66f7:e68e:31d%15
192.168.38.1
fe80:0:0:0:553f:f180:b540:75ff%16

但是我怎样才能获得我的 LAN IP 地址呢?我的局域网IP地址是192.168.10.99。

最佳答案

这个 conde 片段对我帮助很大。

 String IP()
{
String IP_address = "";
int count = 0 ;
try{
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements())
{
NetworkInterface current = interfaces.nextElement();
// System.out.println(current);
if (!current.isUp() || current.isLoopback() || current.isVirtual()) continue;
Enumeration<InetAddress> addresses = current.getInetAddresses();
while (addresses.hasMoreElements()){
InetAddress current_addr = addresses.nextElement();
if (current_addr.isLoopbackAddress()) continue;
if (current_addr instanceof Inet4Address && count == 0)
{
IP_address = current_addr.getHostAddress() ;
System.out.println(current_addr.getHostAddress());
count++;
break;
}
}
}
}
catch(SocketException SE)
{
SE.printStackTrace();
}
return IP_address;
}

关于java - 如何使用JAVA获取局域网IP地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26993435/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com