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

54,877

Solution 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.

Solution 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

Solution 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.

Share:
54,877
JL.
Author by

JL.

Developer, Designer , Coder

Updated on January 12, 2021

Comments

  • JL.
    JL. over 3 years

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

    Thanks