LinuxでのネイティブIPアドレスの取得


次のコードを使用できます.
InetAddress inet = InetAddress.getLocalHost();   
System.out.println("   ip=" + inet.getHostAddress());  

 
 
Windowsの下で仕事ができます.Linuxでは127.0.0.1を返します.主にlinuxで返されるのは、/etc/hostsで構成されたlocalhostのipアドレスであり、NICのバインドアドレスではありません.その後、NICのバインドアドレスを変更し、ネイティブのipアドレスを取得できます:)
コードは次のとおりです.
//          IP   
Enumeration netInterfaces=NetworkInterface.getNetworkInterfaces();   
InetAddress ip = null;   
while(netInterfaces.hasMoreElements())   
{   
    NetworkInterface ni=(NetworkInterface)netInterfaces.nextElement();   
    System.out.println(ni.getName());   
    ip=(InetAddress) ni.getInetAddresses().nextElement();   
    if( !ip.isSiteLocalAddress()   
            && !ip.isLoopbackAddress()   
            && ip.getHostAddress().indexOf(":")==-1)   
    {   
        System.out.println("   ip=" + ip.getHostAddress());   
        break;   
    }   
    else  
    {   
        ip=null;   
    }   
}