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

Posted on

Question :

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


Answer :

There are some criteria that you can use. I believe that the easiest is to get 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 put into controller .

You will only have problems if internal access is done through an external proxy or external access is done by an internal proxy , 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 non-anonymous proxies.

Helper method to verify that the internal network is 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));

You can improve, I do not like using int.Parse() . Obviously it does not address IPv6.


Leave a Reply

Your email address will not be published. Required fields are marked *