如何在C#中获取用户的公共IP地址

我想要使​​用我的网站的客户的公共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(); 

输出:

IP地址:192.168.1.7

请帮我拿到公共IP地址。

这是我使用的:

 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”是显示用户IP的aspx页面中的标签名称。

您可以使用“HTTP_X_FORWARDED_FOR”或“REMOTE_ADDR”标题属性。

请参阅developersnote.com博客的方法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; } 

所有这些build议的组合,以及背后的原因。 随意添加更多的testing用例。 如果获得客户端IP是非常重要的,那么你可能会想要得到所有的结果可能会更准确的比较。

简单检查这个线程中的所有build议,加上一些我自己的代码…

  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; } 

该代码会为您提供服务器的IP地址,而不是访问您的网站的客户端的地址。 使用HttpContext.Current.Request.UserHostAddress属性到客户端的IP地址。

对于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; } 

对于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(); } 

所以这些代码片断中的很多都很大,可能会让新程序员感到困惑。

这个简单而紧凑的代码如何获取访问者的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"]; } 

简单,简短,紧凑。

我有一个扩展方法:

 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; } 

注意:“HTTP_X_FORWARDED_FOR”是代理后面的IP。 context.Request.UserHostAddress与“REMOTE_ADDR”相同。

但是请记住,虽然并不需要实际的IP。

资料来源:

IIS服务器variables

链接

我的版本处理ASP.NET或LAN IP:

 /** * Get visitor's ip address. */ public static string GetVisitorIp() { string ip = null; if (HttpContext.Current != null) { // ASP.NET ip = string.IsNullOrEmpty(HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]) ? HttpContext.Current.Request.UserHostAddress : HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; } if (string.IsNullOrEmpty(ip) || ip.Trim() == "::1") { // still can't decide or is LAN var lan = Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(r => r.AddressFamily == AddressFamily.InterNetwork); ip = lan == null ? string.Empty : lan.ToString(); } return ip; } 
  private string GetClientIpaddress() { string ipAddress = string.Empty; ipAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (ipAddress == "" || ipAddress == null) { ipAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; return ipAddress; } else { return ipAddress; } } 

在MVC 5上,你可以使用这个:

 string cIpAddress = Request.UserHostAddress; //Gets the client ip address 

要么

 string cIpAddress = Request.ServerVariables["REMOTE_ADDR"]; //Gets the client ip address 

在MVC中IP可以通过下面的代码获得

 string ipAddress = Request.ServerVariables["REMOTE_ADDR"]; 
 string IP = HttpContext.Current.Request.Params["HTTP_CLIENT_IP"] ?? HttpContext.Current.Request.UserHostAddress; 

只用这个………………

 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; } 

我们连接到给我们外部IP地址的服务器,并尝试从返回的HTML页面parsingIP。 但是,当服务器对这些页面进行小的更改或删除它们时,这些方法会停止正常工作。

这是一个方法,采取外部IP地址使用已经存活多年的服务器,并快速返回一个简单的响应… https://www.codeproject.com/Tips/452024/Getting-the-External-IP-地址;

 Private string getExternalIp() { try { 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; } catch { return null; } } 

VB.NET

 Imports System.Net Private Function GetExternalIp() As String Try Dim ExternalIP As String 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 Catch Return Nothing End Try 

结束function

lblmessage.Text = Request.ServerVariables [“REMOTE_HOST”]。ToString();