如何获取服务器IP地址,即ASP.NET中服务器的IPv4 [英] How to get the server IP address i.e IPv4 of server in ASP.NET

查看:168
本文介绍了如何获取服务器IP地址,即ASP.NET中服务器的IPv4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试过以下但是在托管应用程序后它返回:: 1作为IP地址。但是,当用户请求网站时,我想知道用户是否请求该特定IP。所以我想检索服务器IPV4地址。



我尝试过:



  private  字符串 GetIPAddress()
{
IPServer = string .Empty;
IPServer = Convert.ToString(HttpContext.Current.Request.ServerVariables [ HTTP_X_FORWARDED_FOR] )!= null ? Convert.ToString(HttpContext.Current.Request.ServerVariables [ HTTP_X_FORWARDED_FOR]): .Empty;

if string .IsNullOrEmpty(IPServer))
{
IPServer = Request.ServerVariables [ REMOTE_ADDR];
}
return IPServer;
}

解决方案

服务器IP地址是静态的 - 或者它应该是 - 意味着它永远不会改变。如果是这样,那么将URLwww.MyDomain.com转换为IP地址的DNS查找将找不到该站点。

这很复杂,但是当用户从浏览器请求URL时,发生以下情况:

浏览器要求操作系统提供服务器IP地址。

操作系统执行DNS查找并将IP地址返回给浏览器。

浏览器创建与服务器的TCP连接,并通过TCP连接发送HHTP请求。

浏览器接收HTTP响应并处理它(授权错误,404等处理在这里)

浏览器将响应呈现为页面。



所有这些都使用IP地址,而不是DNS查找完成后的URL 。



您可以获得服务器IP地址,这很简单:此处显示的 FillInDetails 方法将从服务器和客户端一样容易:使用基于IP的地理位置 - 以及为什么它几乎没用。 [ ^ ]

但它不会改变!

I've tried as below but it's returning ::1 as the IP Address after Hosting the Application. But here when the user requests for the website i want to know whether the user requested to that particular IP or not. So I wanna retrieve the server IPV4 address.

What I have tried:

private String GetIPAddress()   
{
IPServer = string.Empty;   
         IPServer=Convert.ToString(HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]) != null ? Convert.ToString(HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]) : string.Empty;

if (string.IsNullOrEmpty(IPServer))
{
IPServer = Request.ServerVariables["REMOTE_ADDR"];
}                      
return IPServer;
}

解决方案

The server IP address is static - or it should be - meaning it never changes. If it does, then the DNS lookup that converts the URL "www.MyDomain.com" to an IP address would not find the site.
It's complicated, but when the user requests a URL from the browser, the following things happen:
The browser asks the OS for server IP address.
The OS does a DNS lookup and returns the IP address to the browser.
The browser creates a TCP connection to server, and sends an HHTP request via the TCP connection.
The browser receives HTTP response and process it (authorization errors, 404's and suchlike are handled here)
The browser renders response as a page.

All of this uses the IP address, not the URL once the DNS lookup is complete.

You can get the server IP address, that's simple: the FillInDetails method shown here will do it from a server as easily as from a client: Using IP based Geolocation - and why it's pretty much useless.[^]
But it won't change!


这篇关于如何获取服务器IP地址,即ASP.NET中服务器的IPv4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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