2012-09-11 64 views
0

如何使用Java獲取Linux機器的所有IP地址?獲取Linux機器的所有ip地址

我的設備有兩個IP地址,但在嘗試使用下面的方法獲取所有IP地址時,它只會返回一個主IP地址。相同的一段代碼適用於Windows。

InetAddress myAddr = InetAddress.getLocalHost(); 
System.out.println("myaddr::::" + myAddr.getHostName()); 
InetAddress localAddress[] = InetAddress.getAllByName(myAddr.getHostName()); 
int len = localAddress.length; 
for(int i = 0; i < len; i++) 
{ 
    String localaddress = localAddress[i].getHostAddress().trim(); 
    System.out.println("localaddress::::" + localaddress); 
} 
+4

看看[如何獲得通過Java在Linux上的計算機的IP](http://stackoverflow.com/questions/901755/how-to-get-the-ip -of-the-computer-on-linux-through-java) – cubanacan

回答

1

我相信你應該採取NetworkInterfaces級Java的樣子。 您將查詢所有可用的接口並枚舉它們以獲取分配給每個接口的詳細信息(您的案例中的IP地址)。

你可以找到例子和說明Here

希望這有助於

+0

它很好用,非常感謝 – mreaevnia

0

試試這個,你可以得到

InetAddress address = InetAddress.getLocalHost(); 
NetworkInterface neti = NetworkInterface.getByInetAddress(address); 
byte macadd[] = neti.getHardwareAddress(); 
System.out.println(macadd); 
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, UnknownHostException { 
    System.out.println(System.getProperty("os.name")); 
    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"); 
} 
}