简体   繁体   中英

How to get the IP address using C# in asp.net

I want to get the public IP address of the visitor in my code.

I have written below code to get it:

        var context = System.Web.HttpContext.Current;
        string ip = String.Empty;

        if (context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
        {
            ip = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
        }
        else if (!String.IsNullOrWhiteSpace(context.Request.UserHostAddress))
        {
            ip = context.Request.UserHostAddress;                
        }

        if (ip == "::1")
            ip = "127.0.0.1";

        return ip;

I am not getting the exact IP address It returns the value like: fe80::9419:dfb3:22ce:4e88%68 but when I see my IP in What is my IP? it shows 13.67.58.30 . How would I get the exact IP address?

I would recommend against using Request.ServerVariables["HTTP_X_FORWARDED_FOR"] . Reason being that it's being passed by the X-Forwarded-For HTTP header, and all HTTP headers can be spoofed . If using your code, a user could impersonate any IP they wanted by simply replacing the header. Also, it's not guaranteed that all proxies will even place that header in the first place.

You can get the user's IP address by using:

string ip = context.Request.UserHostAddress;

That number you're seeing is most likely the client's IPv6 address.

UserHostAddress. This method gets the IP address of the current request. It uses the UserHostAddress property in the ASP.NET framework. This is the easiest way to get a string representation of the IP address. Example. First, this sample code presents the Application_BeginRequest method, which is executed every time a user visits the web site. You can add it by going to Add -> Global Application Class. In Application_BeginRequest, we get the current HttpRequest, then access the UserHostAddress string property. Finally, we write the string value to the output and complete the request. Method that gets IP address: ASP.NET, C#

using System;
using System.Web;

namespace WebApplication1
{
    public class Global : HttpApplication
    {
    protected void Application_BeginRequest(object sender,
        EventArgs e)
    {
        // Get request.
        HttpRequest request = base.Request;

        // Get UserHostAddress property.
        string address = request.UserHostAddress;

        // Write to response.
        base.Response.Write(address);

        // Done.
        base.CompleteRequest();
    }
    }
}

Result of the application

127.0.0.1

The IP address. In this example, I ran the program on the localhost server, which is one on my computer. In this case, the connection is only a local connection, which means my local address was the IP address returned. Note: If this code was run on a remote server, the IP address for my internet connection would be returned.

Summary. We acquired the current IP address of the user with the UserHostAddress property. This method returns a string with numbers separated by periods. This can be directly used in a Dictionary if you need to record or special-case users by IP.

What you are trying to get with this code is your own IP, anyway this is an old questions, please take a look here .

For me the best response is from mangokun but the response can be enhanced this way:

    protected string GetIPAddress()
    {
        var context = HttpContext.Current;
        var ip = context.Request.ServerVariables["REMOTE_ADDR"];

        if (IsInternal(ip)) {
            string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (!string.IsNullOrEmpty(ipAddress))
                ip = ipAddress.Split(',')[0];
        }

        return ip;
    }

    /* An IP should be considered as internal when:

       ::1          -   IPv6  loopback
       10.0.0.0     -   10.255.255.255  (10/8 prefix)
       127.0.0.0    -   127.255.255.255  (127/8 prefix)
       172.16.0.0   -   172.31.255.255  (172.16/12 prefix)
       192.168.0.0  -   192.168.255.255 (192.168/16 prefix)
     */
    public bool IsInternal(string testIp)
    {
        if(testIp == "::1") return true;

        byte[] ip = IPAddress.Parse(testIp).GetAddressBytes();
        switch (ip[0])
        {
            case 10:
            case 127:
                return true;
            case 172:
                return ip[1] >= 16 && ip[1] < 32;
            case 192:
                return ip[1] == 168;
            default:
                return false;
        }
    }

To get the requesting client IP you can read it using:

 var clientIp = Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ??
                Request.ServerVariables["REMOTE_ADDR"];

The ip-addresses you see is IPv6 addresses so they are valid IP-numbers to, it is up the the client to send the HTTP-headers so there is nothing you can do about that, to bad.

One thing you need to keep in mind is that HTTP_X_FORWARDED_FOR can contain multiple valid IP-numbers.

var listIp = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

clientIp = string.IsNullOrEmpty(listIp) ? Request.ServerVariables["REMOTE_ADDR"]
                                        : listIp.Split(',')[0];
<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
   <title>User's IP Address using ASP.NET</title>
    <script language="C#" runat="server">
        public void Page_Load(Object sender, EventArgs e)
        {
            //Print the time when the page loaded initially
            Response.Write("<span class='logo' />The Page Loaded at: " + DateTime.Now.ToLongTimeString());
            divLANIPAddress.InnerHtml = GetLanIPAddress().Replace("::ffff:","");
        }
        /*
         Method to get the IP Address of the User
         */
        public String GetLanIPAddress()
        {
            //The X-Forwarded-For (XFF) HTTP header field is a de facto standard for identifying the originating IP address of a 
            //client connecting to a web server through an HTTP proxy or load balancer
            String ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

            if (string.IsNullOrEmpty(ip))
            {
                ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }

            return ip;
        }
    </script>
    <style type="text/css">
    body
    {
      background-color:#32373a;
      color:#FFFFFF;
    }
    #mainBody
    {
      background-color:#FFFFFF;
      height:100%;
      color:#32373a;
    }
    .divMainTime
    {
      width:350px;
      height:30px;
      background-color:#fdd136;
      font-size:14px;
      vertical-align:middle;
      padding-top: 5px;
    }
    #divLANIPAddress
    {
        font-size:20px;
        float:right;
        margin-right:10px;
    }
    </style>
</head>
<body>
    <form id="form1" runat="server">

    <div id='mainBody'>
    <h1>
    Retrieve User's IP Address
    </h1>
    <br />
        <div class='divMainTime'>
            <div style='float:left;font-size:18px;'>User's IP Address :</div> 
            <div id="divLANIPAddress" runat="server"></div>
        </div>
    </div>
    </form>
</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM