How To Get IP Address In .Net?

Forums .NETHow To Get IP Address In .Net?
Staff asked 2 weeks ago

Answers (1)

Add Answer
Staff answered 2 weeks ago

Code to get IP Address using Method 1:

private void GetIpValue(out string ipAdd)  
{  
    ipAdd = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];  
  
    if (string.IsNullOrEmpty(ipAdd))  
    {  
        ipAdd = Request.ServerVariables["REMOTE_ADDR"];  
    }  
    else  
    {  
        lblIPAddress.Text = ipAdd;  
    }  
}

Code to get IP Address using Method 2:

private void GetIpAddress(out string userip)  
{  
    userip = Request.UserHostAddress;  
    if (Request.UserHostAddress != null)  
    {  
        Int64 macinfo = new Int64();  
        string macSrc = macinfo.ToString("X");  
        if (macSrc == "0")  
        {  
            if (userip == "127.0.0.1")  
            {  
                Response.Write("visited Localhost!");  
            }  
            else  
            {  
                lblIPAdd.Text = userip;  
            }     
        }  
    }  
}
<!DOCTYPE html>  
  
<html xmlns="http://www.w3.org/1999/xhtml">  
<head runat="server">  
    <title>Get IP Address</title>  
    <link href="Files/css/bootstrap.css" rel="stylesheet" />  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h1><strong>Your IP Address : </strong></h1>  
        <br/>  
        <h1><strong>Method 1 : </strong><asp:Label ID="lblIPAddress" CssClass="label label-primary" runat="server" Text="Label"></asp:Label></h1>  
        <br />  
        <h1><strong>Method 2 : </strong><asp:Label ID="lblIPAdd" CssClass="label label-info" runat="server" Text="Label"></asp:Label></h1>  
    </div>  
    </form>  
</body>  
</html>

 

Subscribe

Select Categories