我正在尝试使用C#获取客户端计算机的IP地址。我使用以下代码获取IP地址:
string IPAddress = HttpContext.Current.Request.UserHostAddress;
但它以编码格式给我回复,fe80::ed13:dee2:127e:1264%13
如何获取实际的IP地址?任何人都面临这个问题请分享一些想法。
答案 0 :(得分:14)
<强> C#强>
string IPAddress = GetIPAddress();
public string GetIPAddress()
{
IPHostEntry Host = default(IPHostEntry);
string Hostname = null;
Hostname = System.Environment.MachineName;
Host = Dns.GetHostEntry(Hostname);
foreach (IPAddress IP in Host.AddressList) {
if (IP.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) {
IPAddress = Convert.ToString(IP);
}
}
return IPAddress;
}
<强> VB.net 强>
Dim Host As IPHostEntry
Dim Hostname As String
Hostname = My.Computer.Name
Host = Dns.GetHostEntry(Hostname)
For Each IP As IPAddress In Host.AddressList
If IP.AddressFamily = System.Net.Sockets.AddressFamily.InterNetwork Then
IPAddress = Convert.ToString(IP)
End If
Next
Return IPAddress
希望这有帮助
答案 1 :(得分:5)
private string GetUserIP()
{
return Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ?? Request.ServerVariables["REMOTE_ADDR"];
}
您可能会获得多个IP地址,因此可以将它们拆分为 -
private string GetUserIP()
{
string ipList = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(ipList))
{
return ipList.Split(',')[0];
}
return Request.ServerVariables["REMOTE_ADDR"];
}
答案 2 :(得分:5)
尝试使用此
string ip=System.Net.Dns.GetHostEntry
(System.Net.Dns.GetHostName()).AddressList.GetValue(0).ToString();
答案 3 :(得分:4)
在我的项目中,需要获取本地PC IP。所以我用它 请尝试以下代码
string strHostName = System.Net.Dns.GetHostName();
IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);
IPAddress[] addr = ipEntry.AddressList;
string ip = addr[1].ToString();