How do I get the IP address of the server that calls my ASP.NET page? I have seen stuff about a Response object, but am very new at c#. Thanks a ton.
+5
A:
This should work:
//this gets the ip address of the server pc
public string GetIPAddress()
{
string strHostName = System.Net.Dns.GetHostName();
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
return ipAddress.ToString();
}
http://wec-library.blogspot.com/2008/03/gets-ip-address-of-server-pc-using-c.html
OR
//while this gets the ip address of the visitor making the call
HttpContext.Current.Request.UserHostAddress;
http://www.geekpedia.com/KB32_How-do-I-get-the-visitors-IP-address.html
TStamper
2009-03-14 19:20:43
Those two code blocks do completely different things.
Martin
2009-03-14 19:24:33
What is the difference?
Jergason
2009-03-14 19:26:59
The top code block gets the IP address of the server that the code is running on. The bottom code block gets the IP address of the visitor who makes the request.
Martin
2009-03-14 19:29:14
The reason I put those two different request up there is for the question. That is why I put two links to go in detail for both, so the understanding was clarified
TStamper
2009-03-14 19:45:12
It even shows the difference in the names of the link.so that was no reason to downvote me
TStamper
2009-03-14 19:47:51
I removed the downvote, but I think you should edit the answer to make it clear which code block does what. What happens if both those websites dissappear off the internet in a few months when someone is looking at this answer?
Martin
2009-03-14 19:50:20
that is true. Changes have been made
TStamper
2009-03-14 20:00:50
Thanks for the clarification guys.
Jergason
2009-03-14 20:59:46
+1
A:
The above is slow as it requires a DNS call (and will obviously not work if one is not available). You can use the code below to get a map of the current pc's local IPV4 addresses with their corresponding subnet mask:
public static Dictionary<IPAddress, IPAddress> GetAllNetworkInterfaceIpv4Addresses()
{
var map = new Dictionary<IPAddress, IPAddress>();
foreach (var ni in NetworkInterface.GetAllNetworkInterfaces())
{
foreach (var uipi in ni.GetIPProperties().UnicastAddresses)
{
if (uipi.Address.AddressFamily != AddressFamily.InterNetwork) continue;
if (uipi.IPv4Mask == null) continue; //ignore 127.0.0.1
map[uipi.Address] = uipi.IPv4Mask;
}
}
return map;
}
warning: this is not implemented in Mono yet
mythz
2010-02-10 19:08:17