How to get the server IP Address (in C# / asp.net)?

Is there a 1 line method to get the IP Address of the server?

Thanks

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Request.ServerVariables["LOCAL_ADDR"];

From the docs:

Returns the server address on which the request came in. This is important on computers where there can be multiple IP addresses bound to the computer, and you want to find out which address the request used.

This is distinct from the Remote addresses which relate to the client machine.

Method 2

From searching the net I found following code: (I couldn’t find a single line method there)

string myHost = System.Net.Dns.GetHostName();

// Show the hostname 

MessageBox.Show(myHost);

// Get the IP from the host name

string myIP = System.Net.Dns.GetHostEntry(myHost).AddressList[index].ToString();

// Show the IP 

MessageBox.Show(myIP);

-> where index is the index of your ip address host (ie. network connection).

Code from: http://www.geekpedia.com/tutorial149_Get-the-IP-address-in-a-Windows-application.html

Method 3

As other(s) have posted, System.Net.Dns.GetHostEntry is the way to go. When you access the AddressList property, you’ll want to take the AddressFamily property into account, as it could return both IPv4 AND IPv6 results.

Method 4

This method will return your machine public IP address when run this code on your PC and when you deploy your application on server will return Server IP address.

public static string Getpublicip()
    {
        try
        {
            string externalIP = "";
            var request = (HttpWebRequest)WebRequest.Create("http://icanhazip.com.ipaddress.com/");
            var response = (HttpWebResponse)request.GetResponse();
            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

            externalIP = new WebClient().DownloadString("http://icanhazip.com");
            return externalIP;

        }
        catch (Exception e)
        {

            return "null";
        }

    }


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x