由于系统上可能连接了多个以太网或wlan,我如何知道哪个网络具有互联网连接?
Enumeration en;
try {
en = NetworkInterface.getNetworkInterfaces();
while (en.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) en.nextElement();
Enumeration ee = ni.getInetAddresses();
System.out.println(ni.getName());
while (ee.hasMoreElements()) {
InetAddress ia = (InetAddress) ee.nextElement();
System.out.println(ia.getHostAddress());
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
答案 0 :(得分:0)
查看以下代码:
public static void main(String[] args) {
Enumeration en;
boolean connected;
int timeOut = 5000;
try {
en = NetworkInterface.getNetworkInterfaces();
while (en.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) en.nextElement();
Enumeration ee = ni.getInetAddresses();
System.out.println(ni.getName());
while (ee.hasMoreElements()) {
InetAddress ia = (InetAddress) ee.nextElement();
ia.getByName("www.google.com");
connected = ia.isReachable(timeOut);
if (connected == true) {
System.out.println(ia.getHostAddress());
}
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}