Javaを使用する私のPCのローカルIPアドレスを検索しようとしました。しかし、結果は正しくありませんでした。具体的には、ipconfig
コマンドからWireless LAN Adapter WiFi IPv4アドレスが必要です。私はthis excellent answerのような多くの異なる質問を見ましたが、Javaでこれをどうやって行うのかは明らかになりませんでした。 InetAddress.getLocalHost()
は、間違ったIP( 'Ethernet-Adapter VirtualBox Host-Only Network')を返します。偽陽性のないローカルマシンのIPアドレスを見つける
Iは、次のコードを試みた:
public static List<String> getLocalIPAddresses() throws Exception
{
val networkInterfaces = NetworkInterface.getNetworkInterfaces();
val localIPAddresses = new ArrayList<String>();
while (networkInterfaces.hasMoreElements())
{
for (val interfaceAddress : networkInterfaces.nextElement().getInterfaceAddresses())
{
val address = interfaceAddress.getAddress();
// Find the local IP addresses
if (address.isSiteLocalAddress())
{
val localIPAddress = interfaceAddress.getAddress().toString().replace("/", "");
localIPAddresses.add(localIPAddress);
}
}
}
if (localIPAddresses.isEmpty())
{
throw new IllegalStateException("Expected the computer's local IP address but didn't get one!");
}
return localIPAddresses;
}
注
val
がLombok
からです。私のマシン上で
が、これは2つのIPアドレスのリストを返します。
192.168.56.1
192.168.2.103
「イーサネットアダプタのVirtualBoxホストオンリーネットワーク」1、正しい「ワイヤレスLANアダプタのWiFi」1。私はいつも後者を保証するために何ができますか?明らかにisSiteLocalAddress()
(a.k.aローカルIPアドレス)を確認するだけでは不十分です。コードワイズでは他に何ができますか? 'VirtualBox'を除外することは、特にネットワークインターフェイス名が言語に依存するため、絶対的な解決策ではありません。
public static List<String> getLocalIPAddresses() throws Exception
{
val networkInterfaces = NetworkInterface.getNetworkInterfaces();
val localIPAddresses = new ArrayList<String>();
while (networkInterfaces.hasMoreElements())
{
val networkInterface = networkInterfaces.nextElement();
val displayName = networkInterface.getDisplayName();
if (!displayName.contains("VirtualBox"))
{
for (val interfaceAddress : networkInterface.getInterfaceAddresses())
{
val address = interfaceAddress.getAddress();
// Find the local IP addresses
if (address.isSiteLocalAddress())
{
val localIPAddress = interfaceAddress.getAddress().toString().replace("/", "");
localIPAddresses.add(localIPAddress);
}
}
}
}
if (localIPAddresses.isEmpty())
{
throw new IllegalStateException("Expected the computer's local IP address but didn't get one!");
}
return localIPAddresses;
}
私はプラットフォームに依存しないソリューションが必要です。私はWindows上だけど。
どちらのIPも同じnetworkInterfaceにありますか?そうでない場合は、interfaceをnetworkIntreface.isVirtual()などのブール値テストと区別できますか? –
@MichaelMcKay: 'isVirtual()'チェックを含めても、コードは2つのIPを返します。彼らはそれぞれ異なるネットワークインターフェイス上にあります。 – BullyWiiPlaza
"InetAddress.getLocalHost()が間違ったIPを返す"場合、それをforループでフィルタリングするために使用できますか? –