开发者

Asp.NET Get current domain

If I have a website running at www.example.com, but someone accesses it by IP address. How can I in code lookup in 开发者_高级运维IIS that www.example.com is the actual site's domain?


It's not possible to reliably look up a domain based on an IP address because an IP address can be mapped to 0 or more domain names.

The best you can do is have a list of mappings. Note that it's also possible for a local network IP address and an external IP point to the same location.

In general, a specific machine can be referenced by several IPs, each of which can be referenced by several domains. So you can go domain > IP address -> machine but not the other way around.


Are you trying to get the IP of www.example.com so you can compare it?

You can get the IP of www.example.com by doing:

 System.Net.Dns.GetHostEntry("www.example.com").AddressList[0].ToString();

You could then compare the IPs to see if they are the same. Also note that there is a list so you could check to see if it exists:

bool ipMatch = (System.Net.Dns.GetHostEntry("www.example.com").
    AddressList.Where(a => a.ToString().Equals(userIP)).Count() > 0);

You could use Contains but then you have to build up an IPAddress object which you probably don't have.

EDIT: From your comment you have the IP and want the host address so just do:

string hostname = System.Net.Dns.GetHostEntry(yourIPHere).HostName;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜