2012-02-28 82 views
1

通过硬编码连接的网络的IP地址,我可以实现android和PC之间的Wi-Fi通信。但我需要获得连接到Wi-Fi网络的系统的IP地址。 Iam使用C#在Windows平台上工作。所以请在这方面帮助我。获取wifi连接系统的IP地址

+0

看看这个链接:http://stackoverflow.com/questions/1069103/how-to-get-my-own-ip-address-in-c – 2012-02-28 18:26:38

+0

看到这个:HTTP:// stackoverflow.com/questions/2518155/other-than-udp-broadcast-or-multicast-what-other-methods-can-i-use-on-a-wifi-ne – arx 2012-02-28 18:29:57

回答

2

这可能会为你工作:

string[] strIP = null; 
int count = 0; 

IPHostEntry HostEntry = Dns.GetHostEntry((Dns.GetHostName())); 
if (HostEntry.AddressList.Length > 0) 
{ 
    strIP = new string[HostEntry.AddressList.Length]; 
    foreach (IPAddress ip in HostEntry.AddressList) 
    { 
     if (ip.AddressFamily == AddressFamily.InterNetwork) 
     { 
      strIP[count] = ip.ToString(); 
      count++; 
     } 
    } 
} 

的问题是,主机可以有多个IP地址。这就是为什么使用字符串数组,它收集所有。

通过L.B--

--EDITED这里是代码的工作版本以上

var addresses = Dns.GetHostEntry((Dns.GetHostName())) 
        .AddressList 
        .Where(x => x.AddressFamily == AddressFamily.InterNetwork) 
        .Select(x => x.ToString()) 
        .ToArray(); 
+1

'HosyEntry',使用'strIP'而没有初始化。等你有没有尝试编译和运行你的代码? – 2012-02-28 19:09:32

+0

是的 - 对不起。当我写这篇文章时(我的电话),我离开了VS。好的编辑+1 – jwddixon 2012-02-28 19:22:55

0

对于UWP,用它来得到你的本地IP地址。根据@ L.B的回答进行更新。

var addresses = Dns.GetHostEntryAsync((Dns.GetHostName())) 
       .Result 
       .AddressList 
       .Where(x => x.AddressFamily == AddressFamily.InterNetwork) 
       .Select(x => x.ToString()) 
       .ToArray();