ASP.NET: How to Get Public IP address in ASP.NET using C# & VB.NET?

It is required sometime to get Public IP Address of Client System in our website in asp,net, just for record or for other purpose. Suppose we want to save IP address for further use to monitor user, how much time he visit the website.

In this article we will learn how to get Public or External IP Address of the client system in asp.net. 
Demo:
In this example I have written the code on Button Click Event:

Asp.NET Code to get Public IP address:
In C#:
  Add Following NameSpaces : 
using System.IO;
using System.Net;
using System.Net.Sockets;

Now Write Following Code:

 protected string GetIPAddress()
    {
String IP = "";
        WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
        using (WebResponse response = request.GetResponse())
        using (StreamReader stream = new StreamReader(response.GetResponseStream()))
        {
            IP = stream.ReadToEnd();
        }
        return IP;
    }
protected void btnIpAddress_Click(object sender, EventArgs e)
    {
        string ipAddress = GetIPAddress();
        Response.Write("IP Address: " + ipAddress);
    }


In VB.NET:
protected Function GetIPAddress() As String
Dim IP As [String] = ""
Dim request As WebRequest = WebRequest.Create("http://checkip.dyndns.org/")
Using response As WebResponse = request.GetResponse()
            Using stream As New StreamReader(response.GetResponseStream())
                        IP = stream.ReadToEnd()
            End Using
End Using
Return IP
   End Function
Protected Sub btnIpAddress_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnIpAddress.Click
        Dim ipAddress As String = GetIPAddress()
        Response.Write("IP Address: " &ipAddress)

End Sub




EmoticonEmoticon