Get local IP address

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

    Modified compman2408's code to be able to iterate through each NetworkInterfaceType.

    public static string GetLocalIPv4 (NetworkInterfaceType _type) {
        string output = null;
        foreach (NetworkInterface item in NetworkInterface.GetAllNetworkInterfaces ()) {
            if (item.NetworkInterfaceType == _type && item.OperationalStatus == OperationalStatus.Up) {
                foreach (UnicastIPAddressInformation ip in item.GetIPProperties ().UnicastAddresses) {
                    if (ip.Address.AddressFamily == AddressFamily.InterNetwork) {
                        output = ip.Address.ToString ();
                    }
                }
            }
        }
        return output;
    }
    

    And you can call it like so:

    static void Main (string[] args) {
        // Get all possible enum values:
        var nitVals = Enum.GetValues (typeof (NetworkInterfaceType)).Cast ();
    
        foreach (var nitVal in nitVals) {
            Console.WriteLine ($"{nitVal} => {GetLocalIPv4 (nitVal) ?? "NULL"}");
        }
    }
    

提交回复
热议问题