Generate class file (business class) to access IP Address using C# and VB.Net in ASP.Net

Last Reply 19 days ago By dharmendr

Posted 19 days ago

How to generate a class file access IpAddress universally

I use ASP.NET WebPages2 with an App_Code folder. 

How can I generate a class file for the following code in my App_Code folder and access it in other pages: 

    var vblip = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
    if (!string.IsNullOrEmpty(vblip))
    {
        string[] addresses = vblip.Split(',');
        if (addresses.Length != 0)
        {
            vblip = addresses[0];
        }
    }
    else
    {
        vblip = System.Web.HttpContext.Current.Request.Headers.Get("CF-Connecting-IP");
        if (String.IsNullOrEmpty(vblip))
        {
            vblip = System.Web.HttpContext.Current.Request.UserHostAddress;
        }
    }

Thanks

Posted 19 days ago

Hi Emma,

Check this example. Now please take its reference and correct your code.

IPClass

C#

public class IPClass
{
    public string GetIPAddress()
    {
        string vblip = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
        if (!string.IsNullOrEmpty(vblip))
        {
            string[] addresses = vblip.Split(',');
            if (addresses.Length != 0)
            {
                vblip = addresses[0];
            }
        }
        else
        {
            vblip = System.Web.HttpContext.Current.Request.Headers.Get("CF-Connecting-IP");
            if (String.IsNullOrEmpty(vblip))
            {
                vblip = System.Web.HttpContext.Current.Request.UserHostAddress;
            }
        }

        return vblip;
    }
}

VB.Net

Public Class IPClass
    Public Function GetIPAddress() As String
        Dim vblip As String = System.Web.HttpContext.Current.Request.ServerVariables("HTTP_X_FORWARDED_FOR")
        If Not String.IsNullOrEmpty(vblip) Then
            Dim addresses As String() = vblip.Split(","c)
            If addresses.Length <> 0 Then
                vblip = addresses(0)
            End If
        Else
            vblip = System.Web.HttpContext.Current.Request.Headers.Get("CF-Connecting-IP")
            If String.IsNullOrEmpty(vblip) Then
                vblip = System.Web.HttpContext.Current.Request.UserHostAddress
            End If
        End If

        Return vblip
    End Function
End Class

Then call it in any page by creating the instance of the class.

C#

protected void Page_Load(object sender, EventArgs e)
{
    IPClass ip = new IPClass();
    string ipAddress = ip.GetIPAddress();
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    Dim ip As IPClass = New IPClass()
    Dim ipAddress As String = ip.GetIPAddress()
End Sub