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

问题描述:

在网上花了很多时间(近2天)后,我从微软发现,类systen.net.IpAddress尚未在UWP上工作(等待他们是预期的日期)。C#从UWP上的连接的WiFi适配器获取IP地址

我在找的是获得连接的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); 
       } 
      } 
     } 
    } 
} 
  • 首先我得到我与“_networkAdapterId”连接适配器的ID
  • 然后我得到我的个人资料与“_connectedProfile”
  • 然后我得到的连接配置文件名称“_profileName”
  • 然后我从NetworkInformation“cnxProfile”模板的列表
  • 连接0

使用功能​​我得到了我的设备上实际连接的所有主机名。

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

GetHostNames() value

Host.Displayname value

在第二张照片,下面IPInformation/NetworkAdapter我们可以找到NetworkAdapterID。

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

最后,我来到了作为解决方案,它看起来没有那么糟糕:)

'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; 
     } 
    } 
} 
+0

现在的目标是获取远程ip地址,这给了我我的IP(换句话说,我的网关从一ip的角度来看)仍然知道ICMP不适用于UWP项目:)欢迎任何想法:)。 – AlainFr74