How do I get the local host IP address in a Window

2019-06-28 08:37发布

问题:

A particular rest service I am calling in a Windows Store app wants the IP address of the calling computer as a parameter. None of the tried and true examples using System.Net or System.Net.NetworkInformation compile in a Store app.

What is the magical combination of types and methods available in a windows store app that will get to the local machine's IP address? I feel like it is probably obvious but I am not seeing it!

回答1:

You will have to contact an external server. Even if the platform supplies an API to retrieve the network address, the host could still be located behind a proxy or a NAT (and you will see something like 192.168.1.4, instead of your external IP address).

Just perform an HTTP request towards services like http://ifconfig.me/ or http://whatismyip.com/ and parse the IP.



回答2:

Local network IP address:

foreach (HostName localHostName in NetworkInformation.GetHostNames())
{
    if (localHostName.IPInformation != null)
    {
        if (localHostName.Type == HostNameType.Ipv4)
        {
            // E.g.: 192.168.1.108
            Debug.WriteLine(localHostName);
        }
    }
}