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

21

429

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 who for example clicked a link. How can I get the real IP Address?

For example, in a Stack Overflow user profile it is: "Last account activity: 4 hours ago from 86.123.127.8", but my machine IP address is a bit different. How does Stack Overflow get this address?

In some web systems there is an IP address check for some purposes. For example, with a certain IP address, for every 24 hours can the user just have only 5 clicks on download links? This IP address should be unique, not for an ISP that has a huge range of clients or Internet users.

Did I understand well?

Singhal answered 9/4, 2009 at 18:19 Comment(3)
They usually do the same thing and don't work correctly for shared IP addresses. Not much can be done in this area.Leicester
What is the problem you are trying to solve here, why do you think you need the IP address?Trawl
i have an application that checks a specific link clicks, and a specific user(by IP) cant click the link more than 5 times in a day.problem is that if Request.UserHostAddress is for a range of users Under an ISP or Network or a specific user's one?Singhal
T
148

As others have said you can't do what you are asking. If you describe the problem you are trying to solve maybe someone can help?

E.g.

  • are you trying to uniquely identify your users?
  • Could you use a cookie, or the session ID perhaps instead of the IP address?

Edit The address you see on the server shouldn't be the ISP's address, as you say that would be a huge range. The address for a home user on broadband will be the address at their router, so every device inside the house will appear on the outside to be the same, but the router uses NAT to ensure that traffic is routed to each device correctly. For users accessing from an office environment the address may well be the same for all users. Sites that use IP address for ID run the risk of getting it very wrong - the examples you give are good ones and they often fail. For example my office is in the UK, the breakout point (where I "appear" to be on the internet) is in another country where our main IT facility is, so from my office my IP address appears to be not in the UK. For this reason I can't access UK only web content, such as the BBC iPlayer). At any given time there would be hundreds, or even thousands, of people at my company who appear to be accessing the web from the same IP address.

When you are writing server code you can never be sure what the IP address you see is referring to. Some users like it this way. Some people deliberately use a proxy or VPN to further confound you.

When you say your machine address is different to the IP address shown on StackOverflow, how are you finding out your machine address? If you are just looking locally using ipconfig or something like that I would expect it to be different for the reasons I outlined above. If you want to double check what the outside world thinks have a look at whatismyipaddress.com/.

This Wikipedia link on NAT will provide you some background on this.

Trawl answered 9/4, 2009 at 18:37 Comment(6)
so I understood in server side applications we cant be sure about IP address. it means that client side programming is the solution?? you mean for example with some JavaScript codes we can do that??Singhal
NO, this would be pointless, the IP address the client "thinks" it has will be internal to the home or office, it will be meaningless in the outside world. E.g. most home routers hand out IP addresses in the range 192.168.1.xxx, so thousands of machines have the same address on their own networks.Trawl
but this is a new Question: if the result of Request.UserHostAddress is unique for each user or not?my purpose is to catch how many times a user clicks on a link by IP address,Request.UserHostAddress can do that?here is not important IP is correct or not challenge is to reach unique ip for each userSinghal
No, it is not unique. Two users behind the same router using NAT will have the same IP address. I really think you need to read up on this, see link in my edit.Trawl
So why do the companies like AWS, Azure etc use ip address in security group rules and allow only that ip-address to connect to the VM?Donatus
@user5950947: Because Azure expect you to be a company with a static public IP address. It is safe to assume that your company only will ever access from its public IP address, so it is a nice added security feature. But IP addresses can be faked or your network can be hacked, so it should never be the only security.Delladelle
E
499

Often you will want to know the IP address of someone visiting your website. While ASP.NET has several ways to do this one of the best ways we've seen is by using the "HTTP_X_FORWARDED_FOR" of the ServerVariables collection.

Here's why...

Sometimes your visitors are behind either a proxy server or a router and the standard Request.UserHostAddress only captures the IP address of the proxy server or router. When this is the case the user's IP address is then stored in the server variable ("HTTP_X_FORWARDED_FOR").

So what we want to do is first check "HTTP_X_FORWARDED_FOR" and if that is empty we then simply return ServerVariables("REMOTE_ADDR").

While this method is not foolproof, it can lead to better results. Below is the ASP.NET code in VB.NET, taken from James Crowley's blog post "Gotcha: HTTP_X_FORWARDED_FOR returns multiple IP addresses"

C#

protected string GetIPAddress()
{
    System.Web.HttpContext context = System.Web.HttpContext.Current; 
    string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

    if (!string.IsNullOrEmpty(ipAddress))
    {
        string[] addresses = ipAddress.Split(',');
        if (addresses.Length != 0)
        {
            return addresses[0];
        }
    }

    return context.Request.ServerVariables["REMOTE_ADDR"];
}

VB.NET

Public Shared Function GetIPAddress() As String
    Dim context As System.Web.HttpContext = System.Web.HttpContext.Current
    Dim sIPAddress As String = context.Request.ServerVariables("HTTP_X_FORWARDED_FOR")
    If String.IsNullOrEmpty(sIPAddress) Then
        Return context.Request.ServerVariables("REMOTE_ADDR")
    Else
        Dim ipArray As String() = sIPAddress.Split(New [Char]() {","c})
        Return ipArray(0)
    End If
End Function
Entrant answered 11/4, 2009 at 17:3 Comment(15)
@deepeshk Are you running it locally in IIS?Discommon
HTTP_X_FORWARDED_FOR must be easy to fake because I have tested this on the first 5 free proxy servers I found and it is always null, therefore returns the proxy servers IP :(Appellee
Be sure to not use this code for security purposes because anyone can fake HTTP_X_FORWARDED_FOR or similar headers. So if you use this for security related logging or security checks, an attacker can bypass it easily.Goliard
From your link, what we actually needed to be doing was take the last IP address, but your code gets the first addresses[0]. Which is correct?Madelina
@NelsonRothermel Based on en.wikipedia.org/wiki/X-Forwarded-For#Format if you want the client (rather than the previous proxy) then use the first.Polluted
@dr.evil So what would you propose instead? Because I want to set access for WCF services by specified IPs.Tufthunter
addresses.Length != 0 is not necessary, since it can never be 0.Spooner
string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; giving me null and context.Request.ServerVariables; returns " ::1 " . What is the problem ?Boaster
@BimalDas you probably try in localhost, try accessing it from another computer so you will see.Hyps
Can context.Request.ServerVariables["REMOTE_ADDR"] be null?Soneson
im curious as to why you are using string.Split() on the IP address. assuming a non-malicious request, how can you get a comma inside an IP Address?Microminiaturization
@elliot-j, HTTP_X_FORWARDED_FOR can contain more than one IP address separated by a comma.Cadaverine
Note: don't use System.Web.HttpContext.Current in Web API projects, see the comments under #9566389 - you can instead use (HttpContextWrapper)Request.Properties["MS_HttpContext"]Paraguay
This does not return the correct ip address for HTTPS requests. Is there a way to get the correct ip address for a HTTPS request?Devlen
Also u can use HttpContext.GetServerVariable("HTTP_X_FORWARDED_FOR")Agile
T
148

As others have said you can't do what you are asking. If you describe the problem you are trying to solve maybe someone can help?

E.g.

  • are you trying to uniquely identify your users?
  • Could you use a cookie, or the session ID perhaps instead of the IP address?

Edit The address you see on the server shouldn't be the ISP's address, as you say that would be a huge range. The address for a home user on broadband will be the address at their router, so every device inside the house will appear on the outside to be the same, but the router uses NAT to ensure that traffic is routed to each device correctly. For users accessing from an office environment the address may well be the same for all users. Sites that use IP address for ID run the risk of getting it very wrong - the examples you give are good ones and they often fail. For example my office is in the UK, the breakout point (where I "appear" to be on the internet) is in another country where our main IT facility is, so from my office my IP address appears to be not in the UK. For this reason I can't access UK only web content, such as the BBC iPlayer). At any given time there would be hundreds, or even thousands, of people at my company who appear to be accessing the web from the same IP address.

When you are writing server code you can never be sure what the IP address you see is referring to. Some users like it this way. Some people deliberately use a proxy or VPN to further confound you.

When you say your machine address is different to the IP address shown on StackOverflow, how are you finding out your machine address? If you are just looking locally using ipconfig or something like that I would expect it to be different for the reasons I outlined above. If you want to double check what the outside world thinks have a look at whatismyipaddress.com/.

This Wikipedia link on NAT will provide you some background on this.

Trawl answered 9/4, 2009 at 18:37 Comment(6)
so I understood in server side applications we cant be sure about IP address. it means that client side programming is the solution?? you mean for example with some JavaScript codes we can do that??Singhal
NO, this would be pointless, the IP address the client "thinks" it has will be internal to the home or office, it will be meaningless in the outside world. E.g. most home routers hand out IP addresses in the range 192.168.1.xxx, so thousands of machines have the same address on their own networks.Trawl
but this is a new Question: if the result of Request.UserHostAddress is unique for each user or not?my purpose is to catch how many times a user clicks on a link by IP address,Request.UserHostAddress can do that?here is not important IP is correct or not challenge is to reach unique ip for each userSinghal
No, it is not unique. Two users behind the same router using NAT will have the same IP address. I really think you need to read up on this, see link in my edit.Trawl
So why do the companies like AWS, Azure etc use ip address in security group rules and allow only that ip-address to connect to the VM?Donatus
@user5950947: Because Azure expect you to be a company with a static public IP address. It is safe to assume that your company only will ever access from its public IP address, so it is a nice added security feature. But IP addresses can be faked or your network can be hacked, so it should never be the only security.Delladelle
S
90

UPDATE: Thanks to Bruno Lopes. If several ip addresses could come then need to use this method:

    private string GetUserIP()
    {
        string ipList = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

        if (!string.IsNullOrEmpty(ipList))
        {
            return ipList.Split(',')[0];
        }

        return Request.ServerVariables["REMOTE_ADDR"];
    }
Scharf answered 5/3, 2012 at 13:27 Comment(6)
As noted in another answers, HTTP_X_FORWARDED_FOR can be a list of IPs, separated by commas.Kendra
In response to the function I just get ::1 every time . Can't I get complete IP address???Ailbert
it will return ::1 on local host. try it on productino environment and it should be fine.Albertson
@farhangdon, the following code will return ip address in local host as @Bat_Programmer wrote below System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList[1].ToString();Albertson
DON'T DO THIS! Be careful not to simply use the first IP address in the list. You should only skip known proxy IPs starting at the rightmost entry to avoid man-in-the-middle attacks and header spoofing.Hyperparathyroidism
Also u can use HttpContext.GetServerVariable("HTTP_X_FORWARDED_FOR")Agile
G
27

If is c# see this way, is very simple

string clientIp = (Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ?? 
                   Request.ServerVariables["REMOTE_ADDR"]).Split(',')[0].Trim();
Grof answered 30/1, 2013 at 14:41 Comment(3)
If both server variables can be null, it can throw exception.Frazzle
What is Request Referencing here? I ServerVariables not foundPump
HttpContext.Current.Request.Mckeehan
L
25

What else do you consider the user IP address? If you want the IP address of the network adapter, I'm afraid there's no possible way to do it in a Web app. If your user is behind NAT or other stuff, you can't get the IP either.

Update: While there are Web sites that use IP to limit the user (like rapidshare), they don't work correctly in NAT environments.

Leicester answered 9/4, 2009 at 18:21 Comment(0)
P
23

I think I should share my experience with you all. Well I see in some situations REMOTE_ADDR will NOT get you what you are looking for. For instance, if you have a Load Balancer behind the scene and if you are trying to get the Client's IP then you will be in trouble. I checked it with my IP masking software plus I also checked with my colleagues being in different continents. So here is my solution.

When I want to know the IP of a client, I try to pick every possible evidence so I could determine if they are unique:

Here I found another sever-var that could help you all if you want to get exact IP of the client side. so I am using : HTTP_X_CLUSTER_CLIENT_IP

HTTP_X_CLUSTER_CLIENT_IP always gets you the exact IP of the client. In any case if its not giving you the value, you should then look for HTTP_X_FORWARDED_FOR as it is the second best candidate to get you the client IP and then the REMOTE_ADDR var which may or may not return you the IP but to me having all these three is what I find the best thing to monitor them.

I hope this helps some guys.

Piffle answered 15/11, 2012 at 16:27 Comment(3)
It needs to say that http_x_... headers can be easily spoofed respect to remote_addr variable. And therefore remote_addr remains the most reliable source for client ip address.Calaboose
@CiroCorvino you are right but when you have your website hosted on a server which is running behind the Load Balancer (as i have already mentioned in my post) then the remote_addr wont give you the IP that you are looking for. I have experienced what you are saying but when I dug in the solution what I have stated works best for me.Piffle
Sorry @KMX, in effect i also use a combination of remote_addr and http_x_forwarded to infer some assumptions about the origin of the request. If you edit your post, i update my voteCalaboose
D
18

You can use:

System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList.GetValue(0).ToString();
Djerba answered 27/9, 2011 at 0:20 Comment(3)
Actually what i have used to get local host ip address is System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList[1].ToString();Albertson
However, I'm getting an error while executing that in fiddle Request for the permission of type 'System.Net.DnsPermission, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.Loquacious
OP asking how to get remote web user's IP, not his own localhost's address.Chimera
K
18

All of the responses so far take into account the non-standardized, but very common, X-Forwarded-For header. There is a standardized Forwarded header which is a little more difficult to parse out. Some examples are as follows:

Forwarded: for="_gazonk"
Forwarded: For="[2001:db8:cafe::17]:4711"
Forwarded: for=192.0.2.60;proto=http;by=203.0.113.43
Forwarded: for=192.0.2.43, for=198.51.100.17

I have written a class that takes both of these headers into account when determining a client's IP address.

using System;
using System.Web;

namespace Util
{
    public static class IP
    {
        public static string GetIPAddress()
        {
            return GetIPAddress(new HttpRequestWrapper(HttpContext.Current.Request));
        }

        internal static string GetIPAddress(HttpRequestBase request)
        {
            // handle standardized 'Forwarded' header
            string forwarded = request.Headers["Forwarded"];
            if (!String.IsNullOrEmpty(forwarded))
            {
                foreach (string segment in forwarded.Split(',')[0].Split(';'))
                {
                    string[] pair = segment.Trim().Split('=');
                    if (pair.Length == 2 && pair[0].Equals("for", StringComparison.OrdinalIgnoreCase))
                    {
                        string ip = pair[1].Trim('"');

                        // IPv6 addresses are always enclosed in square brackets
                        int left = ip.IndexOf('['), right = ip.IndexOf(']');
                        if (left == 0 && right > 0)
                        {
                            return ip.Substring(1, right - 1);
                        }

                        // strip port of IPv4 addresses
                        int colon = ip.IndexOf(':');
                        if (colon != -1)
                        {
                            return ip.Substring(0, colon);
                        }

                        // this will return IPv4, "unknown", and obfuscated addresses
                        return ip;
                    }
                }
            }

            // handle non-standardized 'X-Forwarded-For' header
            string xForwardedFor = request.Headers["X-Forwarded-For"];
            if (!String.IsNullOrEmpty(xForwardedFor))
            {
                return xForwardedFor.Split(',')[0];
            }

            return request.UserHostAddress;
        }
    }
}

Below are some unit tests that I used to validate my solution:

using System.Collections.Specialized;
using System.Web;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UtilTests
{
    [TestClass]
    public class IPTests
    {
        [TestMethod]
        public void TestForwardedObfuscated()
        {
            var request = new HttpRequestMock("for=\"_gazonk\"");
            Assert.AreEqual("_gazonk", Util.IP.GetIPAddress(request));
        }

        [TestMethod]
        public void TestForwardedIPv6()
        {
            var request = new HttpRequestMock("For=\"[2001:db8:cafe::17]:4711\"");
            Assert.AreEqual("2001:db8:cafe::17", Util.IP.GetIPAddress(request));
        }

        [TestMethod]
        public void TestForwardedIPv4()
        {
            var request = new HttpRequestMock("for=192.0.2.60;proto=http;by=203.0.113.43");
            Assert.AreEqual("192.0.2.60", Util.IP.GetIPAddress(request));
        }

        [TestMethod]
        public void TestForwardedIPv4WithPort()
        {
            var request = new HttpRequestMock("for=192.0.2.60:443;proto=http;by=203.0.113.43");
            Assert.AreEqual("192.0.2.60", Util.IP.GetIPAddress(request));
        }

        [TestMethod]
        public void TestForwardedMultiple()
        {
            var request = new HttpRequestMock("for=192.0.2.43, for=198.51.100.17");
            Assert.AreEqual("192.0.2.43", Util.IP.GetIPAddress(request));
        }
    }

    public class HttpRequestMock : HttpRequestBase
    {
        private NameValueCollection headers = new NameValueCollection();

        public HttpRequestMock(string forwarded)
        {
            headers["Forwarded"] = forwarded;
        }

        public override NameValueCollection Headers
        {
            get { return this.headers; }
        }
    }
}
Kalpa answered 12/7, 2017 at 0:11 Comment(1)
Great solution for also handling the standardized Forwarded headerAnneliese
T
14

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.

Tyson answered 9/4, 2009 at 18:32 Comment(3)
That's all well and good, but what do you do when one customer of a multi-tenant system demands that their users' accounts can only login from a specified IP address?Fritz
Then they have to tell you which IP address your server will see. If they need there to be a particular address, then they will not be able to be behind a NAT or similar.Tyson
@RonnieOverby I'm in the same situation. I need to know what IP they are connecting from and it must be on my whitelist. Then the app can turn certain functionality on or off based on their IP. This is what the customer wants.Chimera
W
11

If you are using CloudFlare, you can try this Extension Method:

public static class IPhelper
{
    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) return Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();

        return Request.UserHostAddress;
    }
}

then

string IPAddress = Request.GetIPAddress();
Wellspring answered 23/7, 2016 at 22:3 Comment(1)
And using F5 or Palo Alto ?Wring
P
10
string IP = HttpContext.Current.Request.Params["HTTP_CLIENT_IP"] ?? HttpContext.Current.Request.UserHostAddress;
Pastiness answered 15/7, 2014 at 7:38 Comment(0)
N
7

What you can do is store the router IP of your user and also the forwarded IP and try to make it reliable using both the IPs [External Public and Internal Private]. But again after some days client may be assigned new internal IP from router but it will be more reliable.

Noodle answered 4/8, 2011 at 15:22 Comment(0)
D
7

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;
    }
}
Debor answered 2/1, 2018 at 8:22 Comment(1)
Why do you use HTTP_X_FORWARDED_FOR but not X_FORWARDED_FOR? Are they the same?Henka
O
6
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();
Ostensive answered 22/1, 2020 at 16:42 Comment(0)
C
4

use in ashx file

public string getIP(HttpContext c)
{
    string ips = c.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
    if (!string.IsNullOrEmpty(ips))
    {
        return ips.Split(',')[0];
    }
    return c.Request.ServerVariables["REMOTE_ADDR"];
}
Coextend answered 9/3, 2014 at 7:49 Comment(0)
D
4

Its easy.Try it:

var remoteIpAddress = Request.HttpContext.Connection.RemoteIpAddress;

just it :))

Degas answered 29/1, 2020 at 14:39 Comment(1)
FYI, the above code works only in Asp.Net Core and not the regular Asp.Net linkDiscuss
C
1

In NuGet package install Microsoft.AspNetCore.HttpOverrides Then try:

public class ClientDeviceInfo
    {
        private readonly IHttpContextAccessor httpAccessor;

        public ClientDeviceInfo(IHttpContextAccessor httpAccessor)
        {
            this.httpAccessor = httpAccessor;
        }

        public string GetClientLocalIpAddress()
        {
            return httpAccessor.HttpContext.Connection.LocalIpAddress.ToString();
        }

        public string GetClientRemoteIpAddress()
        {
            return httpAccessor.HttpContext.Connection.RemoteIpAddress.ToString();
        }

        public string GetClientLocalPort()
        {
            return httpAccessor.HttpContext.Connection.LocalPort.ToString();
        }

        public string GetClientRemotePort()
        {
            return httpAccessor.HttpContext.Connection.RemotePort.ToString();
        }
     }
Corabella answered 25/11, 2020 at 21:9 Comment(0)
M
-3

use this

Dns.GetHostEntry(Dns.GetHostName())
Maag answered 9/9, 2012 at 9:39 Comment(1)
Dns.GetHostEntry The GetHostEntry method queries a DNS server for the IP address that is associated with a host name or IP address. Refer msdn.microsoft.com/en-us/library/ms143998(v=vs.80).aspxFancy
W
-4

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>
Weeper answered 31/12, 2018 at 5:5 Comment(1)
An explanation of what this is doing would be helpful, but then this is not even vaguely ASP.NET, let alone server-side, code.Pigment
A
-5

Simply

var ip =  Request.UserHostAddress;

That's all...

enter image description here

Angulation answered 31/8, 2021 at 5:14 Comment(1)
It says right in the first sentence of the question that UserHostAddress doesn't return the IP address they want.Pigment
M
-8

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;
}
Multipartite answered 30/7, 2013 at 14:56 Comment(2)
This returns the server ip addressRedeeming
It's about asp.net, which is a web application, which runs on a server, not on the users computer.Rowlett

© 2022 - 2024 — McMap. All rights reserved.