How to get Unicast, Dns and Gateway Address in UWP?

徘徊边缘 提交于 2019-12-04 16:25:34

问题


I'm trying to find Unicast, Dns and Gateway Address in windows IOT. Normally I can access these values with NetworkInterface.GetAllNetworkInterfaces() method.

But in UWP, that method is missing.

Is there any alternative for getting these values?


回答1:


You could try to PInvoke methods from Iphlpapi.dll. There are several methods that may contain the Unicast, Dns and Gateway info you're looking for, like GetInterfaceInfo(), GetAdaptersInfo(), GetAdaptersAdresses(), etc. Please see a complete list of available methods here: IP Helper Functions - MSDN. Eventually more than one method might be necessary.

As an example on how to do it, here's some sample code from PInvoke.Net retrieving interface names in my local computer, implemented as a standard UWP app:

public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();
    }

    private void Page_Loaded(object sender, RoutedEventArgs e)
    {
        List<string> list = new List<string>();

        IP_INTERFACE_INFO ips = Iphlpapi.GetInterfaceInfo();

        list.Add(string.Format("Adapter count = {0}", ips.NumAdapters));

        foreach (IP_ADAPTER_INDEX_MAP ip in ips.Adapter)
            list.Add(string.Format("Index = {0}, Name = {1}", ip.Index, ip.Name));

        listView1.ItemsSource = list;
    }
}

// PInvoke
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct IP_ADAPTER_INDEX_MAP
{
    public int Index;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = PInvokes.MAX_ADAPTER_NAME)]
    public String Name;
}

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct IP_INTERFACE_INFO
{
    public int NumAdapters;
    public IP_ADAPTER_INDEX_MAP[] Adapter;

    public static IP_INTERFACE_INFO FromByteArray(Byte[] buffer)
    {
        unsafe
        {
            IP_INTERFACE_INFO rv = new IP_INTERFACE_INFO();
            int iNumAdapters = 0;
            Marshal.Copy(buffer, 0, new IntPtr(&iNumAdapters), 4);
            IP_ADAPTER_INDEX_MAP[] adapters = new IP_ADAPTER_INDEX_MAP[iNumAdapters];
            rv.NumAdapters = iNumAdapters;
            rv.Adapter = new IP_ADAPTER_INDEX_MAP[iNumAdapters];
            int offset = sizeof(int);
            for (int i = 0; i < iNumAdapters; i++)
            {
                IP_ADAPTER_INDEX_MAP map = new IP_ADAPTER_INDEX_MAP();
                IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(map));
                Marshal.StructureToPtr(map, ptr, false);
                Marshal.Copy(buffer, offset, ptr, Marshal.SizeOf(map));
                //map = (IP_ADAPTER_INDEX_MAP)Marshal.PtrToStructure(ptr, typeof(IP_ADAPTER_INDEX_MAP));
                map = Marshal.PtrToStructure<IP_ADAPTER_INDEX_MAP>(ptr);
                Marshal.FreeHGlobal(ptr);
                rv.Adapter[i] = map;
                offset += Marshal.SizeOf(map);
            }
            return rv;
        }
    }
}

internal class PInvokes
{
    public const int MAX_ADAPTER_NAME = 128;

    public const int ERROR_INSUFFICIENT_BUFFER = 122;
    public const int ERROR_SUCCESS = 0;

    [DllImport("Iphlpapi.dll", CharSet = CharSet.Unicode)]
    public static extern int GetInterfaceInfo(Byte[] PIfTableBuffer, ref int size);

    [DllImport("Iphlpapi.dll", CharSet = CharSet.Unicode)]
    public static extern int IpReleaseAddress(ref IP_ADAPTER_INDEX_MAP AdapterInfo);
}

public class Iphlpapi
{
    public static IP_INTERFACE_INFO GetInterfaceInfo()
    {
        int size = 0;
        int r = PInvokes.GetInterfaceInfo(null, ref size);
        Byte[] buffer = new Byte[size];
        r = PInvokes.GetInterfaceInfo(buffer, ref size);
        if (r != PInvokes.ERROR_SUCCESS)
            throw new Exception("GetInterfaceInfo returned an error.");
        IP_INTERFACE_INFO info = IP_INTERFACE_INFO.FromByteArray(buffer);
        return info;
    }
}




回答2:


Try this code Snippet I found here: https://social.msdn.microsoft.com/Forums/en-US/27a8b7a8-8071-4bc1-bbd4-e7c1fc2bd8d7/windows-10-iot-core-how-do-you-create-a-tcp-server-and-client?forum=WindowsIoT

    public static string GetDirectConnectionName()
    {
        var icp = NetworkInformation.GetInternetConnectionProfile();
        if (icp != null)
        {
            if(icp.NetworkAdapter.IanaInterfaceType == EthernetIanaType)
            {
                return icp.ProfileName;
            }
        }

        return null;
    }

    public static string GetCurrentNetworkName()
    {
        var icp = NetworkInformation.GetInternetConnectionProfile();
        if (icp != null)
        {
            return icp.ProfileName;
        }

        var resourceLoader = ResourceLoader.GetForCurrentView();
        var msg = resourceLoader.GetString("NoInternetConnection");
        return msg;
    }

    public static string GetCurrentIpv4Address()
    {
        var icp = NetworkInformation.GetInternetConnectionProfile();
        if (icp != null && icp.NetworkAdapter != null && icp.NetworkAdapter.NetworkAdapterId != null)
        {
            var name = icp.ProfileName;

            var hostnames = NetworkInformation.GetHostNames();

            foreach (var hn in hostnames)
            {
                if (hn.IPInformation != null &&
                    hn.IPInformation.NetworkAdapter != null &&
                    hn.IPInformation.NetworkAdapter.NetworkAdapterId != null &&
                    hn.IPInformation.NetworkAdapter.NetworkAdapterId == icp.NetworkAdapter.NetworkAdapterId &&
                    hn.Type == HostNameType.Ipv4)
                {
                    return hn.CanonicalName;
                }
            }
        }

        var resourceLoader = ResourceLoader.GetForCurrentView();
        var msg = resourceLoader.GetString("NoInternetConnection");
        return msg;
    }



回答3:


As jstreet commented, Invoke is the solution. I tried with a Lumia 950, and GetAdaptersInfo() works, not as IcmpSendEcho().

With the following link you should do it: http://www.pinvoke.net/default.aspx/iphlpapi/GetAdaptersInfo.html



来源:https://stackoverflow.com/questions/32672520/how-to-get-unicast-dns-and-gateway-address-in-uwp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!