Ehtsham
Ehtsham

Reputation: 228

Get IPAddress from a hostname

I want to get IP address of a host on my aspx page using C#, I'm using DNS class methods to get these.

It worked fine locally, but when I deployed the solution on IIS7 it returned only the IP address assigned by ISP but I want local IP address of that machine.

Any suggestion?

Upvotes: 1

Views: 3815

Answers (4)

Jayesh Sorathia
Jayesh Sorathia

Reputation: 1614

Here is Example for this. In this example we can get IP address of our given host name.

    string strHostName = "www.microsoft.com";
    // Get DNS entry of specified host name
    IPAddress[] addresses = Dns.GetHostEntry(strHostName).AddressList;

    // The DNS entry may contains more than one IP addresses.
    // Iterate them and display each along with the type of address (AddressFamily).
    foreach (IPAddress address in addresses)
    {
        Response.Write(string.Format("{0} = {1} ({2})", strHostName, address, address.AddressFamily));
        Response.Write("<br/><br/>");
    }

Upvotes: 1

Muhammad Akhtar
Muhammad Akhtar

Reputation: 52241

you can use this method...

public static String GetIP()
{
    String ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

   if(string.IsNullOrEmpty(ip))
    {
        ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
    }

    return ip;
}

Upvotes: 0

Anders Abel
Anders Abel

Reputation: 69260

When looking up the ip address in a public DNS, you will get the officiall IP address communicated outwards. If NAT is used and you want the internal address you have to connect to a DNS server which holds the internal IP addresses.

Upvotes: 0

iain
iain

Reputation: 1941

I'm fairly confident that you can not get the local 192.168.C.D address of the local machine like this.

This is because of security and visibility (NAT's etc).

If you are looking to uniquely identify a user. I would look to sessions or cookies.

Upvotes: 0

Related Questions