c#获取本地IP地址
场景:C#怎么获取本地IP地址(小弟我有无线网络IP地址)
C#如何获取本地IP地址(我有无线网络IP地址)
网上查了 获取IP地址 都是这样做的 但我有本地连接和无线网络 两个IP地址
string strHostName = Dns.GetHostName();
string clientIPAddress = System.Net.Dns.GetHostAddresses(strHostName).GetValue(1).ToString();
我如何区分获取的是本地的还是无线网络的?我需要的是本地IP地址
------解决方案--------------------
System.Net.Dns.GetHostAddresses(strHostName)
返回的不是一个数组吗?你只取了第一个IP,其它的没有取到。你循环一下试试看:
C#如何获取本地IP地址(我有无线网络IP地址)
网上查了 获取IP地址 都是这样做的 但我有本地连接和无线网络 两个IP地址
string strHostName = Dns.GetHostName();
string clientIPAddress = System.Net.Dns.GetHostAddresses(strHostName).GetValue(1).ToString();
我如何区分获取的是本地的还是无线网络的?我需要的是本地IP地址
------解决方案--------------------
System.Net.Dns.GetHostAddresses(strHostName)
返回的不是一个数组吗?你只取了第一个IP,其它的没有取到。你循环一下试试看:
- C# code
string strHostName = Dns.GetHostName(); foreach (IPAddress ip in System.Net.Dns.GetHostAddresses(strHostName)) { Console.WriteLine(ip.ToString()); }
------解决方案--------------------
- C# code
using System.Net.NetworkInformation; 。 。 。 NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface ni in interfaces) { if (ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet) { MessageBox.Show(ni.Name); } }
------解决方案--------------------
IPHostEntry hostInfo = Dns.GetHostByName(hostString);
hostInfo.AddressList[0];
------解决方案--------------------
ip = Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString()
ip = Request.ServerVariables["REMOTE_ADDR"].ToString()
------解决方案--------------------
- C# code
//试试这个 NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface ni in interfaces) { if (ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet) { foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses) { if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { MessageBox.Show(ip.Address.ToString()); } } } }
------解决方案--------------------
另:由于微软的APIPA机制,可能会出现一个169.254.*.*这样的地址。。。