Get local IP address

前端 未结 26 2609
野的像风
野的像风 2020-11-22 10:07

In the internet there are several places that show you how to get an IP address. And a lot of them look like this example:

String strHostName = string.Empty;         


        
26条回答
  •  难免孤独
    2020-11-22 10:46

    I also was struggling with obtaining the correct IP.

    I tried a variety of the solutions here but none provided me the desired affect. Almost all of the conditional tests that was provided caused no address to be used.

    This is what worked for me, hope it helps...

    var firstAddress = (from address in NetworkInterface.GetAllNetworkInterfaces().Select(x => x.GetIPProperties()).SelectMany(x => x.UnicastAddresses).Select(x => x.Address)
                        where !IPAddress.IsLoopback(address) && address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork
                        select address).FirstOrDefault();
    
    Console.WriteLine(firstAddress);
    

提交回复
热议问题