2013-07-29 21 views
0

我必須確定接入是否來自我的本地網絡(與我的服務器相同的網絡)或來自互聯網。 (使用ASP.NET)如何識別用戶是否在ASP.NET內部或外部我的網絡

我打算創建一個額外的安全..我的意思是,如果訪問是從外部來的,我將只允許「特定用戶」。

我試圖在網上搜索,但我什麼也沒找到。

在此先感謝。

+0

「我的服務器的同一網絡」非常主觀,具體取決於您的網絡佈局。 10.50.0.84是否與10.110.48.22網絡相同?這些IP地址會改變嗎?來自互聯網的流量是如何到達您的服務器的(是否存在反向代理服務器?是否存在外部認證?)這些只是我想到的一些問題。我認爲在將解決方案放在一起之前,您需要進行交流以改進要求。 –

回答

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); 
    } 

其中IsInSameSubnet地址檢查,如果是在同一個網絡

例如:

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; 
     } 
相關問題