Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

asp.net

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

Thanks

like image 820
JL. Avatar asked Aug 28 '09 08:08

JL.


People also ask

How do I find the IP of my C server?

Here is a simple method to find hostname and IP address using C program. gethostname() : The gethostname function retrieves the standard host name for the local computer. gethostbyname() : The gethostbyname function retrieves host information corresponding to a host name from a host database.

What is IP address in C program?

The IPv4 addresses are represented in dot-decimal notation. There are four decimal numbers (all are ranging from 0 to 255). These four numbers are separated by three dots. An example of a valid IP is: 192.168.4.1.

How do I find client IP address in socket programming?

OK assuming you are using IPV4 then do the following: struct sockaddr_in* pV4Addr = (struct sockaddr_in*)&client_addr; struct in_addr ipAddr = pV4Addr->sin_addr; If you then want the ip address as a string then do the following: char str[INET_ADDRSTRLEN]; inet_ntop( AF_INET, &ipAddr, str, INET_ADDRSTRLEN );


3 Answers

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.

like image 98
Zhaph - Ben Duguid Avatar answered Sep 29 '22 14:09

Zhaph - Ben Duguid


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

like image 42
Faizan S. Avatar answered Oct 02 '22 14:10

Faizan S.


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.

like image 30
Mark Carpenter Avatar answered Sep 28 '22 14:09

Mark Carpenter