83

すべてのネットワーク インターフェイスをIPv4アドレスで取得する方法を知る必要があります。または、ワイヤレスとイーサネットだけです。

すべてのネットワーク インターフェイスの詳細を取得するには、次を使用します。

foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces()) {
    if(ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 ||
       ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet) {

        Console.WriteLine(ni.Name);
    }
}

そして、ホストされているコンピューターのすべての IPv4 アドレスを取得するには:

IPAddress [] IPS = Dns.GetHostAddresses(Dns.GetHostName());
foreach (IPAddress ip in IPS) {
    if (ip.AddressFamily == AddressFamily.InterNetwork) {

        Console.WriteLine("IP address: " + ip);
    }
}

しかし、ネットワーク インターフェイスとその正しい ipv4 アドレスを取得するにはどうすればよいでしょうか。

4

3 に答える 3

126
foreach(NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
   if(ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
   {
       Console.WriteLine(ni.Name);
       foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
       {
           if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
           {
               Console.WriteLine(ip.Address.ToString());
           }
       }
   }  
}

これにより、必要なものが得られるはずです。ip.Address は、必要な IPAddress です。

于 2012-04-08T03:51:00.740 に答える