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

Aman Sharma
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 
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("");
        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);

protected Function GetIPAddress() As String
Dim IP As [String] = ""
Dim request As WebRequest = WebRequest.Create("")
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

Post a Comment

Post a Comment

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !