How do I know if a client is accessing the server over the local network or the internet?

Asked

Viewed 600 times

4

How do I identify if the client who is accessing my application, whether it is within the company (local network) or outside (internet)?

  • Take a look at [tour]. You can accept an answer if it solved your problem. You can vote on every post on the site as well. Did any help you more? You need something to be improved?

1 answer

3

There are some criteria that can be used. I believe that the easiest is to take the IP and check if it is in the possible range of the internal network. This can be done with the property Request.UserHostAddress. ideally this should be placed in the controller.

You will only have problems if the internal access is done through a proxy external or external access is made by a proxy internal, which is highly unlikely. The same goes for Vpns. If this is something that can happen, there is no way to know reliably, unless you can establish some other rule that only you know what it can be. There are some ways to try to identify proxies unannounced.

Auxiliary method to verify that it is internal network compliant RFC 1918 (may not be right for you):

public bool isIpPrivate (IPAddress ipAddress) {
    var ipAddressParts = ipAddress.ToString().Split(new String[] { "." });
    var ipAddressParsed = new int[] { int.Parse(ipAddressParts[0]),
        int.Parse(ipAddressParts[1]),  int.Parse(ipAddressParts[2]),
        int.Parse(ipAddressParts[3]) };
    return ipAddressParsed [0] == 10 ||
        (ipAddressParsed [0] == 192 && ipAddressParsed [1] == 168) ||
        (ipAddressParsed [0] == 172 && (ipAddressParsed [1] >= 16 &&
        ipAddressParsed [1] <= 31));
}

I put in the Github for future reference.

I can improve, I don’t like to use the int.Parse().

Obviously does not treat Ipv6.

Documentation

Browser other questions tagged

You are not signed in. Login or sign up in order to post.