Get local IP address

前端 未结 26 2987
野的像风
野的像风 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:42

    Using these:

    using System.Net;
    using System.Net.Sockets;
    using System.Net.NetworkInformation;
    using System.Linq;
    

    You can use a series of LINQ methods to grab the most preferred IP address.

    public static bool IsIPv4(IPAddress ipa) => ipa.AddressFamily == AddressFamily.InterNetwork;
    
    public static IPAddress GetMainIPv4() => NetworkInterface.GetAllNetworkInterfaces()
    .Select((ni)=>ni.GetIPProperties())
    .Where((ip)=> ip.GatewayAddresses.Where((ga) => IsIPv4(ga.Address)).Count() > 0)
    .FirstOrDefault()?.UnicastAddresses?
    .Where((ua) => IsIPv4(ua.Address))?.FirstOrDefault()?.Address;
    

    This simply finds the first Network Interface that has an IPv4 Default Gateway, and gets the first IPv4 address on that interface. Networking stacks are designed to have only one Default Gateway, and therefore the one with a Default Gateway, is the best one.

    WARNING: If you have an abnormal setup where the main adapter has more than one IPv4 Address, this will grab only the first one. (The solution to grabbing the best one in that scenario involves grabbing the Gateway IP, and checking to see which Unicast IP is in the same subnet as the Gateway IP Address, which would kill our ability to create a pretty LINQ method based solution, as well as being a LOT more code)

提交回复
热议问题