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

2019-06-28 08:02发布

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!

2条回答
女痞
2楼-- · 2019-06-28 08:31

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.

查看更多
闹够了就滚
3楼-- · 2019-06-28 08:48

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);
        }
    }
}
查看更多
登录 后发表回答