Sunday 22 December 2013

How to Get User IP address in ASP.NET using C#/VB.NET

Hi Friends, in this article I will explain about How to Get User IP address in ASP.NET using C#/VB.NET.
In C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class GetIpAddress : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write(getIPAddress());
    }
    public static string getIPAddress()
    {
        string ip = string.Empty;
    ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
        if (!string.IsNullOrEmpty(ip))
        {
            string[] ipRange = ip.Split(',');
            int le = ipRange.Length - 1;
            string trueIP = ipRange[le];
        }
        else
        {
            // ip = Request.ServerVariables("REMOTE_ADDR");
            ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
        }

       return "Your IP is: " + ip;       
    }

}
In VB.NET:
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls

Partial Public Class GetIpAddress
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        Response.Write(getIPAddress())
    End Sub
    Public Shared Function getIPAddress() As String
        Dim ip As String = String.Empty
        ip = HttpContext.Current.Request.ServerVariables("HTTP_X_FORWARDED_FOR")
        If Not String.IsNullOrEmpty(ip) Then
            Dim ipRange As String() = ip.Split(","c)
            Dim le As Integer = ipRange.Length - 1
            Dim trueIP As String = ipRange(le)
        Else
            ' ip = Request.ServerVariables("REMOTE_ADDR");
            ip = HttpContext.Current.Request.ServerVariables("REMOTE_ADDR")
        End If

        Return "Your IP is: " & ip
    End Function

End Class

The Output of the above code will show the IP Address.




"If you like my blog or articles, you can appreciate by leaving your comments or Liking my Facebook pageAspdotnet-kishore, following on Google+ Aspdotnet-Kishore, Twitter  on AspdotnetKishore, Linked in Aspdotnet-Kishore, stumbling my posts on stumble upon and subscribing on  RSSfeed Aspdotnet-Kishore for free updates directly to your Email inbox . Watch my blog  for more articles."



No comments:

Post a Comment

© 2012-2018 Aspdotnet-Kishore.blogspot.com. All Rights Reserved.
The content is copyrighted to Kishore and may not be reproduced on other websites without permission from the owner.