Getting IP Info with ASP.NET 4.0 and C#
Adding the Default.aspx Page
To view the IP information we will be getting we will need a simple web site that will allow us to display some data. At this point, I have created a new ASP.NET Empty Web Site. First, we need to add in a Web Form with some labels on it. To do this:
- Right click the project in your Solution Explorer.
- Select Add New Item…
- Select a Web Form.
- Name it Default.aspx.
- Click Add.
- Open Default.aspx up to Design mode.
- Drag and drop a Label onto the Web Form.
- Change the ID property of the Label to ‘lblLocal’.
- Add a line break after the label.
- Drag and drop another Label under lblLocal.
- Change the ID property of the Label to ‘lblRemote’.
Getting the IP Information in C#
Next, we want to add some code on the Page_Load event of our Default.aspx page that will set lblLocal to display the local IP address and will set lblRemote to display the remote address. To do this:
1. Open Default.aspx.cs up for editing.
2. At the top of the class add the following statement:
3. In the Page_Load event method add the following code:
protected void Page_Load(object sender, EventArgs e)
//Local IP Address
string hostName = Dns.GetHostName();
IPHostEntry localIp = Dns.GetHostEntry(hostName);
lblLocal.Text = localIp.AddressList.ToString();
// Remote IP Address
string remoteIp = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
remoteIp = Request.ServerVariables["REMOTE_ADDR"];
lblRemote.Text = remoteIp;
Let’s review what this code is doing. First, we get the hostname of our DNS and set that to our ‘hostName’ string variable. Then, we pass this to the GetHostEntry method that will return an IPHostEntry object which we name ‘localIp’. Next, we set the Text property of lblLocal to the localIp.AddressList property at index of 1 and then convert that to a string. The index used here depends on your computer’s configuration and which IP you want to display. For computers that have IPv6 enabled, index 0 will be the IPv6 with the index of 1 being IPv4.
Then, we use the Request.ServerVariables to attempt to access “HTTP_X_FORWARDED_FOR” and store that in our remoteIp variable. If this fails to return the remote IP we then attempt to access “REMOTE_ADDR”. Then, we simply display that in lblRemote.
To test this out, simply load up the web site and verify that the labels show the correct information for your local and remote IP addresses.