0

I have to identify if the acess is comming from my local network (the same network of my server) or is comming from the internet. (using ASP.NET)

I'm planning to create a extra security.. I mean, if the access is comming from outside, I will "allow" specifics users only.

I tried to search on the web but I found nothing.

Thanks in advance.

4

1 回答 1

0

你可以做这样的事情(虚拟代码)

  private bool IsInSameSubnet(IPAddress address, IPAddress address2, IPAddress subnetMask) {
            bool isInSameSubnet = false;
            IPAddress network1 = GetNetworkAddress(address, subnetMask);
            IPAddress network2 = GetNetworkAddress(address2, subnetMask);
            if (network1 != null && network2 != null) {
                isInSameSubnet = network1.Equals(network2);
            }
            return isInSameSubnet;
        }
    private IPAddress GetNetworkAddress(IPAddress address, IPAddress subnetMask) {

        byte[] ipAdressBytes = address.GetAddressBytes();
        byte[] subnetMaskBytes = subnetMask.GetAddressBytes();

        if (ipAdressBytes.Length != subnetMaskBytes.Length)
            return null;
        //throw new ArgumentException("Lengths of IP address and subnet mask do not match.");

        byte[] broadcastAddress = new byte[ipAdressBytes.Length];
        for (int i = 0; i < broadcastAddress.Length; i++) {
            broadcastAddress[i] = (byte)(ipAdressBytes[i] & (subnetMaskBytes[i]));
        }
        return new IPAddress(broadcastAddress);
    }

where IsInSameSubnetaddress 检查它是否在同一个网络中

例子 :

string computerIP = getIP();

            IPAddress ip1 = IPAddress.Parse(computerIP);
            IPAddress ip2 = IPAddress.Parse("192.168.0.0");
            IPAddress subnetMask = IPAddress.Parse("255.255.0.0");

getIp方法

 public static string getIP() {
            //if user behind proxy this should get it
            string ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (ip != null && ip.Split(',').Count() > 1) {
                //if (ip.Split(',').Count() > 1)
                ip = ip.Split(',')[0];
            }

            //if user not behind proxy this should do it
            if (ip == null)
                ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            return ip;
        }
于 2013-07-29T14:45:53.523 回答