How to get a user's client IP address in ASP.NET?

前端 未结 19 2546
时光取名叫无心
时光取名叫无心 2020-11-22 00:26

We have Request.UserHostAddress to get the IP address in ASP.NET, but this is usually the user\'s ISP\'s IP address, not exactly the user\'s machine IP address

相关标签:
19条回答
  • 2020-11-22 01:01

    Hello guys Most of the codes you will find will return you server ip address not client ip address .however this code returns correct client ip address.Give it a try. For More info just check this

    https://www.youtube.com/watch?v=Nkf37DsxYjI

    for getting your local ip address using javascript you can use put this code inside your script tag

    <script>
        var RTCPeerConnection = /*window.RTCPeerConnection ||*/
         window.webkitRTCPeerConnection || window.mozRTCPeerConnection;
    
             if (RTCPeerConnection) (function () {
                 var rtc = new RTCPeerConnection({ iceServers: [] });
                 if (1 || window.mozRTCPeerConnection) {      
                     rtc.createDataChannel('', { reliable: false });
                 };
    
                 rtc.onicecandidate = function (evt) {
    
                     if (evt.candidate)
                         grepSDP("a=" + evt.candidate.candidate);
                 };
                 rtc.createOffer(function (offerDesc) {
                     grepSDP(offerDesc.sdp);
                     rtc.setLocalDescription(offerDesc);
                 }, function (e) { console.warn("offer failed", e); });
    
    
                 var addrs = Object.create(null);
                 addrs["0.0.0.0"] = false;
                 function updateDisplay(newAddr) {
                     if (newAddr in addrs) return;
                     else addrs[newAddr] = true;
                     var displayAddrs = Object.keys(addrs).filter(function
    (k) { return addrs[k]; });
                     document.getElementById('list').textContent =
    displayAddrs.join(" or perhaps ") || "n/a";
                 }
    
                 function grepSDP(sdp) {
                     var hosts = [];
                     sdp.split('\r\n').forEach(function (line) { 
                         if (~line.indexOf("a=candidate")) {   
                             var parts = line.split(' '),   
                                 addr = parts[4],
                                 type = parts[7];
                             if (type === 'host') updateDisplay(addr);
                         } else if (~line.indexOf("c=")) {      
                             var parts = line.split(' '),
                                 addr = parts[2];
                             updateDisplay(addr);
                         }
                     });
                 }
             })(); else
             {
                 document.getElementById('list').innerHTML = "<code>ifconfig| grep inet | grep -v inet6 | cut -d\" \" -f2 | tail -n1</code>";
                 document.getElementById('list').nextSibling.textContent = "In Chrome and Firefox your IP should display automatically, by the power of WebRTCskull.";
    
             }
    
    
    
    
    </script>
    <body>
    <div id="list"></div>
    </body>
    

    and For getting your public ip address you can use put this code inside your script tag

      function getIP(json) {
        document.write("My public IP address is: ", json.ip);
      }
    
    
    <script type="application/javascript" src="https://api.ipify.org?format=jsonp&callback=getIP"></script>
    
    0 讨论(0)
  • 2020-11-22 01:02

    You can use:

    System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList.GetValue(0).ToString();
    
    0 讨论(0)
  • 2020-11-22 01:02
    public static class Utility
    {
        public static string GetClientIP(this System.Web.UI.Page page)
        {
            string _ipList = page.Request.Headers["CF-CONNECTING-IP"].ToString();
            if (!string.IsNullOrWhiteSpace(_ipList))
            {
                return _ipList.Split(',')[0].Trim();
            }
            else
            {
                _ipList = page.Request.ServerVariables["HTTP_X_CLUSTER_CLIENT_IP"];
                if (!string.IsNullOrWhiteSpace(_ipList))
                {
                    return _ipList.Split(',')[0].Trim();
                }
                else
                {
                    _ipList = page.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                    if (!string.IsNullOrWhiteSpace(_ipList))
                    {
                        return _ipList.Split(',')[0].Trim();
                    }
                    else
                    {
                        return page.Request.ServerVariables["REMOTE_ADDR"].ToString().Trim();
                    }
                }
            }
        }
    }
    

    Use;

    string _ip = this.GetClientIP();
    
    0 讨论(0)
  • 2020-11-22 01:03

    Try:

    using System.Net;
    
    public static string GetIpAddress()  // Get IP Address
    {
        string ip = "";     
        IPHostEntry ipEntry = Dns.GetHostEntry(GetCompCode());
        IPAddress[] addr = ipEntry.AddressList;
        ip = addr[2].ToString();
        return ip;
    }
    public static string GetCompCode()  // Get Computer Name
    {   
        string strHostName = "";
        strHostName = Dns.GetHostName();
        return strHostName;
    }
    
    0 讨论(0)
  • 2020-11-22 01:04

    IP addresses are part of the Network layer in the "seven-layer stack". The Network layer can do whatever it wants to do with the IP address. That's what happens with a proxy server, NAT, relay, or whatever.

    The Application layer should not depend on the IP address in any way. In particular, an IP Address is not meant to be an identifier of anything other than the idenfitier of one end of a network connection. As soon as a connection is closed, you should expect the IP address (of the same user) to change.

    0 讨论(0)
  • 2020-11-22 01:05

    Combining the answers from @Tony and @mangokun, I have created the following extension method:

    public static class RequestExtensions
    {
        public static string GetIPAddress(this HttpRequest Request)
        {
            if (Request.Headers["CF-CONNECTING-IP"] != null) return Request.Headers["CF-CONNECTING-IP"].ToString();
    
            if (Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
            {
                string ipAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
    
                if (!string.IsNullOrEmpty(ipAddress))
                {
                    string[] addresses = ipAddress.Split(',');
                    if (addresses.Length != 0)
                    {
                        return addresses[0];
                    }
                }
            }
    
            return Request.UserHostAddress;
        }
    }
    
    0 讨论(0)
提交回复
热议问题