问题描述
我需要获得用户ipaddress ....我使用下面的代码
i need to get user ipaddress....i use below code
private string GetIP()
{
string strHostName = "";
strHostName = System.Net.Dns.GetHostName();
IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);
IPAddress[] addr = ipEntry.AddressList;
return addr[addr.Length - 1].ToString();
}
它在本地网站上运行...但是在发布我的网站后它返回ipaddress格式如下:
2001:0:4137:9e76:3c60:3e18:935c:505
i不知道我的错误..我怎样才能得到ipaddress。 ..
如果有人知道我的错误解释了我..
谢谢你提前..
it worked in local site...But after publish my site it returns ipaddress in the below format:
"2001:0:4137:9e76:3c60:3e18:935c:505"
i don't know my mistake.. How can i get ipaddress...
if anyone know my mistake explain me..
Thanks n advance..
推荐答案
public static IEnumerable<string> GetAddresses()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
return (from ip in host.AddressList where ip.AddressFamily == AddressFamily.InterNetwork select ip.ToString()).ToList();
}
</string>
上述解决方案AddressFamily.InterNetwork过滤来自AddressFamily的IP4地址。
如果你想要你的系统有效的IP地址,我个人建议在下面的解决方案
on the above solution AddressFamily.InterNetwork filters the IP4 address from AddressFamily.
If you want your system valid IP address, I personally suggest below solution
public static IPAddress GetIPAddress(string hostName)
{
Ping ping = new Ping();
var replay = ping.Send(hostName);
if (replay.Status == IPStatus.Success)
{
return replay.Address;
}
return null;
}
public static void Main()
{
Console.WriteLine("Local IP Address: " + GetIPAddress(Dns.GetHostName()));
Console.WriteLine("Google IP:" + GetIPAddress("google.com");
Console.ReadLine();
}
using System;
using System.Net;
public class IPNetworking
{
public string GetIP4Address()
{
string IP4Address = String.Empty;
foreach (IPAddress IPA in Dns.GetHostAddresses(Request.ServerVariables["REMOTE_ADDR"].ToString())))
{
if (IPA.AddressFamily.ToString() == "InterNetwork")
{
IP4Address = IPA.ToString();
break;
}
}
if (IP4Address != String.Empty)
{
return IP4Address;
}
foreach (IPAddress IPA in Dns.GetHostAddresses(Dns.GetHostName()))
{
if (IPA.AddressFamily.ToString() == "InterNetwork")
{
IP4Address = IPA.ToString();
break;
}
}
return IP4Address;
}
}
string ip = "";
string strHostName = "";
strHostName = System.Net.Dns.GetHostName();
IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);
IPAddress[] addr = ipEntry.AddressList;
ip = addr[2].ToString();
这篇关于如何使用c#获取用户IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!