Identify if request is coming from local network (intranet)

后端 未结 4 1535
名媛妹妹
名媛妹妹 2021-02-06 02:43

I need to identify if a request comes from Internet or Intranet using either client-side or server-side.

The problem I\'m trying to solve is: our web site can be accesse

4条回答
  •  隐瞒了意图╮
    2021-02-06 03:29

    This is how I would do the ip check:

    string ipString = System.Web.HttpContext.Current.Request.UserHostAddress;
    byte[] ipBytes = System.Net.IPAddress.Parse(ipString).GetAddressBytes();
    int ip = System.BitConverter.ToInt32(ipBytes, 0);
    
    // your network ip range
    string ipStringFrom = "192.168.1.0";
    byte[] ipBytesFrom = System.Net.IPAddress.Parse(ipStringFrom).GetAddressBytes();
    int ipFrom = System.BitConverter.ToInt32(ipBytesFrom, 0);
    
    string ipStringTo = "192.168.1.255";
    byte[] ipBytesTo= System.Net.IPAddress.Parse(ipStringTo).GetAddressBytes();
    int ipTo = System.BitConverter.ToInt32(ipBytesFrom, 0);
    
    bool clientIsOnLAN = ipFrom >= ip && ip <= ipTo;
    

    If you have multiple subnets, just do the same for them (from, to), then add to the bool condition above. I just realized that, in your case, the above may be an overkill.

    Alternatively, for you, it might be as simple as:

    bool isOnLAN = System.Web.HttpContext.Current.Request.UserHostAddress.StartsWith("192.168.1.")
    

提交回复
热议问题