日期:2014-05-18  浏览次数:21261 次

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.*.*这样的地址。。。
引用自“网络”,未经过实际测试:
如何禁止APIPA

APIPA是Automatic Private IP Addressing的缩写。它的作用就是在一个没有DHCP的小型
网络中,客户机通过给自己配置169.254.x.x类型的IP地址使自己获得IP配置的机制。如果
不希望让这一机制生效,可以通过编辑注册表:
打开注册表编辑器;
找到HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Inte
rfaces,找到相应的接口号;
加入DWORD类型的IPAutoconfigurationEnabled项设置其值为0;
退出注册表编辑器即可
如果用户有多个网络适配器,并且希望它们都不能进行APIPA,可以设置HKEY_LOCAL_MACH
INE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\IPAutoconfigurationEnab
led为0即可。