如何在C#中获取用户的公共IP地址
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19285957/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the public IP address of a user in C#
提问by Neeraj Mehta
I want the public IP address of the client who is using my website. The code below is showing the local IP in the LAN, but I want the public IP of the client.
我想要使用我网站的客户端的公共 IP 地址。下面的代码显示了局域网中的本地IP,但我想要客户端的公共IP。
//get mac address
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
String sMacAddress = string.Empty;
foreach (NetworkInterface adapter in nics)
{
if (sMacAddress == String.Empty)// only return MAC Address from first card
{
IPInterfaceProperties properties = adapter.GetIPProperties();
sMacAddress = adapter.GetPhysicalAddress().ToString();
}
}
// To Get IP Address
string IPHost = Dns.GetHostName();
string IP = Dns.GetHostByName(IPHost).AddressList[0].ToString();
Output:
输出:
Ip Address : 192.168.1.7
IP地址:192.168.1.7
Please help me to get the public IP address.
请帮我获取公共IP地址。
回答by shf301
That code gets you the IP address of your server not the address of the client who is accessing your website. Use the HttpContext.Current.Request.UserHostAddressproperty to the client's IP address.
该代码为您提供服务器的 IP 地址,而不是访问您网站的客户端的地址。将HttpContext.Current.Request.UserHostAddress属性用于客户端的 IP 地址。
回答by FeliceM
This is what I use:
这是我使用的:
protected void GetUser_IP()
{
string VisitorsIPAddr = string.Empty;
if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
{
VisitorsIPAddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}
else if (HttpContext.Current.Request.UserHostAddress.Length != 0)
{
VisitorsIPAddr = HttpContext.Current.Request.UserHostAddress;
}
uip.Text = "Your IP is: " + VisitorsIPAddr;
}
"uip" is the name of the label in the aspx page that shows the user IP.
“uip”是aspx页面中显示用户IP的标签名称。
回答by BonDaviD
In MVC IP can be obtained by the following Code
在MVC中IP可以通过以下代码获取
string ipAddress = Request.ServerVariables["REMOTE_ADDR"];
回答by shamcs
You can use "HTTP_X_FORWARDED_FOR" or "REMOTE_ADDR" header attribute.
您可以使用“HTTP_X_FORWARDED_FOR”或“REMOTE_ADDR”标头属性。
Refer method GetVisitorIPAddress from Machine Syntax blog .
请参阅机器语法博客中的GetVisitorIPAddress 方法。
/// <summary>
/// method to get Client ip address
/// </summary>
/// <param name="GetLan"> set to true if want to get local(LAN) Connected ip address</param>
/// <returns></returns>
public static string GetVisitorIPAddress(bool GetLan = false)
{
string visitorIPAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (String.IsNullOrEmpty(visitorIPAddress))
visitorIPAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
if (string.IsNullOrEmpty(visitorIPAddress))
visitorIPAddress = HttpContext.Current.Request.UserHostAddress;
if (string.IsNullOrEmpty(visitorIPAddress) || visitorIPAddress.Trim() == "::1")
{
GetLan = true;
visitorIPAddress = string.Empty;
}
if (GetLan && string.IsNullOrEmpty(visitorIPAddress))
{
//This is for Local(LAN) Connected ID Address
string stringHostName = Dns.GetHostName();
//Get Ip Host Entry
IPHostEntry ipHostEntries = Dns.GetHostEntry(stringHostName);
//Get Ip Address From The Ip Host Entry Address List
IPAddress[] arrIpAddress = ipHostEntries.AddressList;
try
{
visitorIPAddress = arrIpAddress[arrIpAddress.Length - 2].ToString();
}
catch
{
try
{
visitorIPAddress = arrIpAddress[0].ToString();
}
catch
{
try
{
arrIpAddress = Dns.GetHostAddresses(stringHostName);
visitorIPAddress = arrIpAddress[0].ToString();
}
catch
{
visitorIPAddress = "127.0.0.1";
}
}
}
}
return visitorIPAddress;
}
回答by user3100230
So many of these code snippets are really big and could confuse new programmers looking for help.
许多这些代码片段非常大,可能会使寻求帮助的新程序员感到困惑。
How about this simple and compact code to fetch the IP address of the visitor?
这个简单而紧凑的代码来获取访问者的IP地址怎么样?
string ip = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ip))
{
ip = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
Simple, short and compact.
简单,简短,紧凑。
回答by GorkemHalulu
string IP = HttpContext.Current.Request.Params["HTTP_CLIENT_IP"] ?? HttpContext.Current.Request.UserHostAddress;
回答by John Suit
Combination of all of these suggestions, and the reasons behind them. Feel free to add more test cases too. If getting the client IP is of utmost importance, than you might wan to get all of theses are run some comparisons on which result might be more accurate.
所有这些建议的组合,以及它们背后的原因。也可以随意添加更多测试用例。如果获取客户端 IP 是最重要的,那么您可能希望获得所有这些都运行一些比较结果可能更准确。
Simple check of all suggestions in this thread plus some of my own code...
简单检查此线程中的所有建议以及我自己的一些代码...
using System.IO;
using System.Net;
public string GetUserIP()
{
string strIP = String.Empty;
HttpRequest httpReq = HttpContext.Current.Request;
//test for non-standard proxy server designations of client's IP
if (httpReq.ServerVariables["HTTP_CLIENT_IP"] != null)
{
strIP = httpReq.ServerVariables["HTTP_CLIENT_IP"].ToString();
}
else if (httpReq.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
{
strIP = httpReq.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}
//test for host address reported by the server
else if
(
//if exists
(httpReq.UserHostAddress.Length != 0)
&&
//and if not localhost IPV6 or localhost name
((httpReq.UserHostAddress != "::1") || (httpReq.UserHostAddress != "localhost"))
)
{
strIP = httpReq.UserHostAddress;
}
//finally, if all else fails, get the IP from a web scrape of another server
else
{
WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
using (WebResponse response = request.GetResponse())
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
strIP = sr.ReadToEnd();
}
//scrape ip from the html
int i1 = strIP.IndexOf("Address: ") + 9;
int i2 = strIP.LastIndexOf("</body>");
strIP = strIP.Substring(i1, i2 - i1);
}
return strIP;
}
回答by Stephen Zeng
I have an extension method:
我有一个扩展方法:
public static string GetIp(this HttpContextBase context)
{
if (context == null || context.Request == null)
return string.Empty;
return context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]
?? context.Request.UserHostAddress;
}
Note: "HTTP_X_FORWARDED_FOR" is for ip behind proxy. context.Request.UserHostAddress is identical to "REMOTE_ADDR".
注意:“HTTP_X_FORWARDED_FOR”用于代理后面的ip。context.Request.UserHostAddress 与“REMOTE_ADDR”相同。
But bear in mind it is not necessary the actual IP though.
但请记住,实际 IP 并不是必需的。
Sources:
资料来源:
回答by Jeetendra Negi
just use this..................
就用这个…………
public string GetIP()
{
string externalIP = "";
externalIP = (new WebClient()).DownloadString("http://checkip.dyndns.org/");
externalIP = (new Regex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")).Matches(externalIP)[0].ToString();
return externalIP;
}
回答by Peyman Mehrabani
For Web Applications ( ASP.NET MVC and WebForm )
对于 Web 应用程序(ASP.NET MVC 和 WebForm)
/// <summary>
/// Get current user ip address.
/// </summary>
/// <returns>The IP Address</returns>
public static string GetUserIPAddress()
{
var context = System.Web.HttpContext.Current;
string ip = String.Empty;
if (context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
ip = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
else if (!String.IsNullOrWhiteSpace(context.Request.UserHostAddress))
ip = context.Request.UserHostAddress;
if (ip == "::1")
ip = "127.0.0.1";
return ip;
}
For Windows Applications ( Windows Form, Console, Windows Service , ... )
对于 Windows 应用程序(Windows 窗体、控制台、Windows 服务,...)
static void Main(string[] args)
{
HTTPGet req = new HTTPGet();
req.Request("http://checkip.dyndns.org");
string[] a = req.ResponseBody.Split(':');
string a2 = a[1].Substring(1);
string[] a3=a2.Split('<');
string a4 = a3[0];
Console.WriteLine(a4);
Console.ReadLine();
}