views:

1243

answers:

2

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
Those two code blocks do completely different things.
Martin
What is the difference?
Jergason
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
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
It even shows the difference in the names of the link.so that was no reason to downvote me
TStamper
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
that is true. Changes have been made
TStamper
Thanks for the clarification guys.
Jergason
+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