所以我尝试从一个特定的界面以编程方式获取IP地址并将其显示在文本字段中。问题是它列出了几个。你如何迭代并获得双频无线-AC 3160的IP地址?
Dual Band Wireless-AC 3160 172.16.36.50
Dual Band Wireless-AC 3160 fe80:0:0:0:8877:2e6a:e4a1:c24f%wlan0
Virtual Ethernet Adapter for VMnet1 192.168.31.1
Virtual Ethernet Adapter for VMnet1 fe80:0:0:0:592c:71ac:f8d9:5899%eth3
Virtual Ethernet Adapter for VMnet8 192.168.245.1
Virtual Ethernet Adapter for VMnet8 fe80:0:0:0:ed34:4a7:cb5c:16ce%eth4
以下是我用来显示界面的代码:
String ip;
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
int position;
while (interfaces.hasMoreElements()) {
NetworkInterface iface = interfaces.nextElement();
//This filters out the interfaces
// filters out 127.0.0.1 and inactive interfaces
if (iface.isLoopback() || !iface.isUp())
continue;
Enumeration<InetAddress> addresses = iface.getInetAddresses();
while(addresses.hasMoreElements()) {
InetAddress addr = addresses.nextElement();
ip = addr.getHostAddress();
System.out.println(iface.getDisplayName() + " " + ip);
}
}
} catch (SocketException e) {
throw new RuntimeException(e);
}
答案 0 :(得分:1)
您将获得两个IP地址,因为该接口有两个IP地址。总的来说可能还会有更多。
如果您只想列出IPv4地址,可以检查地址是否为instanceof Inet4Address
。
答案 1 :(得分:1)
我通过以下方式解决了这个问题。谢谢。
String ip;
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
int position =0;
while (interfaces.hasMoreElements()) {
NetworkInterface iface = interfaces.nextElement();
//This filters out the interfaces
// filters out 127.0.0.1 and inactive interfaces
if (iface.isLoopback() || !iface.isUp())
continue;
Enumeration<InetAddress> addresses = iface.getInetAddresses();
while(addresses.hasMoreElements()) {
InetAddress addr = addresses.nextElement();
ip = addr.getHostAddress();
position++;
if (position == 0 ) {
System.out.println(iface.getDisplayName() + " " + ip);
}
else{
break;
}
}
}
} catch (SocketException e) {
throw new RuntimeException(e);
}
答案 2 :(得分:0)
使用此代码
import java.io.*;
import java.net.*;
import java.util.*;
import static java.lang.System.out;
public class ListNets {
public static void main(String args[]) throws SocketException {
Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
for (NetworkInterface netint : Collections.list(nets))
displayInterfaceInformation(netint);
}
static void displayInterfaceInformation(NetworkInterface netint) throws SocketException {
out.printf("Display name: %s\n", netint.getDisplayName());
out.printf("Name: %s\n", netint.getName());
Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
for (InetAddress inetAddress : Collections.list(inetAddresses)) {
out.printf("InetAddress: %s\n", inetAddress);
}
out.printf("\n");
}
}