C#从UWP上连接的wifi适配器获取IP地址

时间:2017-03-09 15:56:28

标签: uwp

在网上花了很多时间(将近2天)后,我发现微软已经发现类systen.net.IpAddress在UWP上尚未运行(等待它们的预期日期)。 / p>

我正在寻找的是获取连接的wifi适配器的ipaddress。这看起来很简单,但我在一个地狱循环中运行,希望你能帮助我。

1名称使用的空间:

using System; 
using System.Collections.Generic; 
using Windows.UI.Xaml; 
using Windows.UI.Xaml.Controls; 
using Windows.UI.Xaml.Navigation; 
using Windows.Devices.WiFi; 
using Windows.Networking.Connectivity; 
using Windows.Security.Credentials; 
using System.Linq; 
using Windows.Devices.Enumeration;

2 - 顶部的变量(尚未使用全部)

//For wifi adapter choosen by the user
private WiFiAdapter wifiSelectedAdapter;
//For wifi network to connect to choosen by the user
private WiFiAvailableNetwork wifiSelectedNetwork;
//For the connection profile
private ConnectionProfile connectionProfile;
private DeviceInformationCollection deviceInfoCollection;
private IPInformation ipInformation;
private string _string;
private string cnxProfile;
private object _object;

3查找可用的适配器

protected override async void OnNavigatedTo(NavigationEventArgs e)
{
    //Request wifi access from the device
    var access = await WiFiAdapter.RequestAccessAsync();
    if (access != WiFiAccessStatus.Allowed)
    {
        tblDebug.Text = "Access denied";
    }
    else
    {
        DataContext = this;
        // Find all wifi adapters on the equipment
        deviceInfoCollection = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector());
        if (deviceInfoCollection.Count < 1)
        {
            tblDebug.Text = "No WiFi Adapters detected on you device.";
        }
        else
        {
            List<object> ls = new List<object>();
            var test = 0;
            foreach (var item in deviceInfoCollection)
            {
                ls.Add(item.Name);
                test = test + 1;
            }
            ListViewResult.ItemsSource = ls;
            tblDebug.Text = "Please select the wifi adapter to scan with and click scan button";
            btScan.Visibility = Visibility.Visible;
        }
    }
}

4 - 选择适配器并开始扫描

private void ListViewResult_ItemClick(object sender, ItemClickEventArgs e)
{
    _string = e.ClickedItem as string;
    tblDebug.Text = "";
}
private async void btScan_Click(object sender, RoutedEventArgs e)
{
    if (_string == null)
    {
        tblDebug.Text = "Please select an adapter before scanning wifi network";
    }
    else
    {
        foreach (var selecteditem in deviceInfoCollection)
        {
            if (selecteditem.Name == _string)
            {
                var _id = selecteditem.Id;
                try
                {
                    //var access = await WiFiAdapter.RequestAccessAsync();
                    wifiSelectedAdapter = await WiFiAdapter.FromIdAsync(_id);
                }
                catch (Exception ex)
                {
                    throw;
                }
            }
        }
        //Clear ListView previous adapters list
        ListViewResult.ItemsSource = null;
        tblDebug.Text = "";
        //Scan wifi available network
        await wifiSelectedAdapter.ScanAsync();

        //Populate ListView with available wifi network
        List<string> ls = new List<string>();
        var test = 0;
        foreach (var network in wifiSelectedAdapter.NetworkReport.AvailableNetworks)
        {
            ls.Add(network.Ssid);
            test = test + 1;
        }
        ListViewResult.ItemsSource = ls;

        if (test <= 0)
        {
            tblDebug.Text = "No wifi network found.";
        }
        else
        {
            tblDebug.Text = "Select the network in the list, you want to connect to and click Connect button.";
            btConnect.Visibility = Visibility.Visible;
            tblWifiNetwork.Text = "We found the following network(s) :";
        }
    }
}

5选择网络并连接

private async void btConnect_Click(object sender, RoutedEventArgs e)
{
    foreach (var selecteditem in wifiSelectedAdapter.NetworkReport.AvailableNetworks)
    {
        if (selecteditem.Ssid == _string)
        {
            wifiSelectedNetwork = selecteditem;
        }
    }

    //Empty the ListViewResult
    ListViewResult.ItemsSource = null;

    //Create the reconnection Kind to be passed for the connection
    WiFiReconnectionKind reconnectionKind = WiFiReconnectionKind.Automatic;

    // Create the result to catch the connection result
    WiFiConnectionResult result;

    if (wifiSelectedNetwork.SecuritySettings.NetworkAuthenticationType == NetworkAuthenticationType.Open80211 &&
wifiSelectedNetwork.SecuritySettings.NetworkEncryptionType == NetworkEncryptionType.None)
    {
        tblWifiNetwork.Text = "";
        result = await wifiSelectedAdapter.ConnectAsync(wifiSelectedNetwork, reconnectionKind);
        connectionProfile = await wifiSelectedAdapter.NetworkAdapter.GetConnectedProfileAsync();
        cnxProfile = connectionProfile.ProfileName;


        btDisconnect.Visibility = Visibility.Visible;

        if (result.ConnectionStatus == WiFiConnectionStatus.Success)
        {
            tblDebug.Text = "You are connected to " + cnxProfile + " with ip ";// + ttt.ToString();
            btDisconnect.Visibility = Visibility.Visible;
            btIpaddress.Visibility = Visibility.Visible;
        }
        else
        {
            tblDebug.Text = "Sorry but we can't connect you to the selected network.";
            wifiSelectedAdapter.Disconnect();
        }
    }
    else
    {
        gridSecKey.Visibility = Visibility.Visible;
        tblDebug.Text = "The network you are trying to connect to is secured, please enter the security key.";

        // Only the password portion of the credential need to be supplied
        var credential = new PasswordCredential();

        if (!string.IsNullOrEmpty(pwNetworkKey.Password))
        {
            credential.Password = pwNetworkKey.Password;
            result = await wifiSelectedAdapter.ConnectAsync(wifiSelectedNetwork, reconnectionKind, credential);
        }
        else
        {
            tblDebug.Text = "Please enter the security key before connecting.";
            return;
        }
    }
}

在这个阶段,我连接到所需的wifinetwork。

6这就是我被困的地方

private async void btIpaddress_Click(object sender, RoutedEventArgs e)
{
    var _networkAdapterId = wifiSelectedAdapter.NetworkAdapter.NetworkAdapterId;
    var _connectedProfile = await wifiSelectedAdapter.NetworkAdapter.GetConnectedProfileAsync();
    var _profileName = _connectedProfile.ProfileName;
    var cnxProfile = NetworkInformation.GetConnectionProfiles().ToList();
    List<object> _list = new List<object>();
    foreach (var item in cnxProfile)
    {
        if (_profileName == item.ProfileName)
        {
            List<string> ipAddress = new List<string>();
            var Hosts = NetworkInformation.GetHostNames();
            foreach (var Host in Hosts)
            {
                var tt = Host.DisplayName;
                {
                    string IP = Host.DisplayName;
                    ipAddress.Add(IP);
                }
            }
        }
    }
}
  • 首先,我获取了与#34; _networkAdapterId&#34;
  • 相关联的适配器的ID
  • 然后我得到了我与#34; _connectedProfile&#34;
  • 相关联的个人资料
  • 然后我获得连接的个人资料名称&#34; _profileName&#34;
  • 然后我从NetworkInformation获得了个人资料列表&#34; cnxProfile&#34;

使用NetworkInformation.GetHostNames();功能,我可以在设备上实际连接所有主机名。

问题:如何将_networkAdapterId与函数NetworkInformation.GetHostNames()中的相关主机名相关联?

GetHostNames() value

Host.Displayname value

在第二张图片中,在IPInformation / NetworkAdapter下方,我们可以找到NetworkAdapterID。

换句话说,从这个NetworkAdapterID,我如何在UWP上检索它的IP地址?

1 个答案:

答案 0 :(得分:1)

最后,我找到了看起来不那么糟糕的解决方案:)

'var _networkAdapterId = wifiSelectedAdapter.NetworkAdapter.NetworkAdapterId;
 var connectedProfile = NetworkInformation.GetConnectionProfiles().ToList();
 foreach (var item in connectedProfile)
 {
    if (_networkAdapterId == item.NetworkAdapter.NetworkAdapterId)
    {
        var hostname = NetworkInformation.GetHostNames()
                           .SingleOrDefault(
                                hn =>
                                hn.IPInformation != null && hn.IPInformation.NetworkAdapter != null
                                && hn.IPInformation.NetworkAdapter.NetworkAdapterId
                                == _networkAdapterId);
        if (hostname != null)
        {
           // the ip address
           _connectedIpAddress = hostname.CanonicalName;
        }
    }
}