如何在C#中获取客户端机器的IP地址? [英] How to get client machine ip address in C#?

查看:201
本文介绍了如何在C#中获取客户端机器的IP地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在服务器testserver中托管了我的mvc应用程序。

我正在尝试获取客户端IP地址,但是没有获得显示null的值。





你能帮我解决一下如何获取IP地址。

相同的代码在本地机器上获取ipaddress但服务器没有。



我尝试过:



我试过了

private string GetClientIPAddress()

{

string clientIPAddress = string.Empty;

try

{

clientIPAddress = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName())。AddressList.GetValue(0).ToString();

IPHostEntry Host = default(IPHostEntry);

string Hostname = null;

Hostname = System.Environment.MachineName;

Host = Dns.GetHostEntry(Hostname) ;

foreach(Host.AddressList中的IPAddress IP)

{

if(IP.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)

{

clientIPAddress = Convert.ToString(IP);

}

}

}

catch

{

clientIPAddress =;

}

返回clientIPAddress;

}



在本地但不在服务器上工作。

I have hosted my mvc application in server "testserver".
and i am trying to get client IP address but that is not getting value displaying null.


Could you please help me how to get ip address.
same code is getting ipaddress in local machine but no from server.

What I have tried:

I have tried
private string GetClientIPAddress()
{
string clientIPAddress = string.Empty;
try
{
clientIPAddress = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList.GetValue(0).ToString();
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)
{
clientIPAddress = Convert.ToString(IP);
}
}
}
catch
{
clientIPAddress = "";
}
return clientIPAddress;
}

working in local but not in server.

推荐答案

C#代码是在服务器而不是客户端上执行 - 因此任何访问网络适配器的尝试都将访问服务器信息,而不是客户端。

您需要使用 HttpRequest.UserHostAddress Prop erty(System.Web) [ ^ ]。
C# code is executed on the server, not the client - so any attempts to access a network adaptor will access the server information, not the client.
You need to use the HttpRequest.UserHostAddress Property (System.Web)[^] instead.


这篇关于如何在C#中获取客户端机器的IP地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆