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:

  1. Right click the project in your Solution Explorer.
  2. Select Add New Item…
  3. Select a Web Form.
  4. Name it Default.aspx.
  5. Click Add.
  6. Open Default.aspx up to Design mode.
  7. Drag and drop a Label onto the Web Form.
  8. Change the ID property of the Label to ‘lblLocal’.
  9. Add a line break after the label.
  10. Drag and drop another Label under lblLocal.
  11. 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:

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.

Download Source Files