起初:沒有一個地址。您的機器至少有兩個地址(「lo」上爲127.0.0.1,「eth1」上爲192.168.1.1)。
你想這樣的:Listing network interfaces
正如你所期待,你不能自動檢測出連接到任何你的路由器的,因爲這需要你的路由表的潛在複雜的分析。但如果你只是想要任何非本地地址,這應該足夠了。可以肯定的是,至少在Vista或Windows 7上至少使用一次,因爲它們會添加IPv6地址。
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");
}
}
以下是從例如程序輸出樣本:
Display name: bge0
Name: bge0
InetAddress: /fe80:0:0:0:203:baff:fef2:e99d%2
InetAddress: /121.153.225.59
Display name: lo0
Name: lo0
InetAddress: /0:0:0:0:0:0:0:1%1
InetAddress: /127.0.0.1
+1 for'if(cur.isLoopback())' – aioobe 2010-05-16 20:20:21
如果你有很多接口呢?例如,一個用於電纜,一個用於wifi,一個用於虛擬盒子等等。是不可能實際看到哪一個連接到網絡? – cragiz 2010-05-16 21:05:23
@亨利克。在這種情況下,所有這些都是「連接」的。由您的操作系統決定哪一個將用於外部路由。你可以使用這個Socket構造函數http://java.sun.com/j2se/1.5.0/docs/api/java/net/Socket.html#Socket(java.net.InetAddress,%20int,%20java.net。 InetAddress,%20int)來選擇特定的本地地址和端口,或者構建默認套接字並將其綁定到特定接口。另外,請檢查您是否可以從NetworkInterface對象確定需要的信息。 – 2010-05-17 11:56:03