Linux で発生する可能性が高いのはInetAddress.getLocalHost()、ループバック アドレス (127/8、通常は 127.0.0.1) を返すことです。したがって、/etc/hostsファイルから取得した名前はlocalhost.localdomain.
正しいアドレス/ホスト名を取得するには、代わりに次のコードを使用できます。これにより、ネットワーク インターフェイス (私の例では) に関連付けられているすべての IP アドレスが一覧表示eth0され、属していない IPv4 が選択されます。ループバック クラス。
try {
// Replace eth0 with your interface name
NetworkInterface i = NetworkInterface.getByName("eth0");
if (i != null) {
Enumeration<InetAddress> iplist = i.getInetAddresses();
InetAddress addr = null;
while (iplist.hasMoreElements()) {
InetAddress ad = iplist.nextElement();
byte bs[] = ad.getAddress();
if (bs.length == 4 && bs[0] != 127) {
addr = ad;
// You could also display the host name here, to
// see the whole list, and remove the break.
break;
}
}
if (addr != null) {
System.out.println( addr.getCanonicalHostName() );
}
} catch (...) { ... }
すべてのアドレスを表示するようにコードを少し変更できます。コード内のコメントを参照してください。
編集
@rafalmag で提案されているように、他の NIC を反復処理することもできます。
NetworkInterface.getByName("eth0") の代わりに NetworkInterface.getNetworkInterfaces() を繰り返すことをお勧めします