62,073
社区成员
发帖
与我相关
我的任务
分享
#region 判断用户是内网访问还是外网访问
/// <summary>
/// 判断访问的用户是在内网还是外网
/// </summary>
/// <returns>true内网,false外网</returns>
public static bool IsLANIP()
{
string serverSubnet = GetSubnet();//服务器子网掩码
if (string.IsNullOrEmpty(serverSubnet)) //如果网关为空,则可能是网络掉线(在服务器访问的网站)
return true;
string clientIP = IPAddress;
if (clientIP == "127.0.0.1")
return true;
string serverLANIP = System.Net.Dns.GetHostAddresses(System.Net.Dns.GetHostName()).GetValue(0).ToString();//服务器内网IP
string serverNetID = GetNetID(serverLANIP, serverSubnet);
string clientNetID = GetNetID(clientIP, serverSubnet);
return serverNetID == clientNetID;
}
/// <summary>
/// 根据ip和子网掩码计算出网络ID
/// </summary>
/// <param name="ip">ip地址</param>
/// <param name="subnetMask">子网掩码</param>
/// <returns>网络ID</returns>
public static string GetNetID(string ip, string subnet)
{
string[] tempIP = ip.Split('.');
int tIP = 0;
int iIP = 0;
int iMask = 0;
for (int i = 0; i < 4; i++) // 把IP从字符串的表示形式改成整型的形式
{
tIP = byte.Parse(tempIP[i]);
iIP += (tIP << (3 - i) * 8);
}
tempIP = subnet.Split('.');
for (int i = 0; i < 4; i++) // 把掩码从字符串的表示形式改成整型的形式
{
tIP = byte.Parse(tempIP[i]);
iMask += (tIP << (3 - i) * 8);
}
tIP = iIP & iMask;
string netID = ((byte)(tIP >> 24)).ToString(); // 网络ID, IP段
for (int i = 1; i < 4; i++)
{
netID += "." + ((byte)(tIP >> (3 - i) * 8)).ToString();
}
return netID;
}
/// <summary>
/// 获取服务器子网掩码
/// </summary>
/// <returns></returns>
public static string GetSubnet()
{
string subnet = string.Empty;
foreach (System.Net.NetworkInformation.NetworkInterface f in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces())
{
System.Net.NetworkInformation.IPInterfaceProperties ipInterface = f.GetIPProperties();
foreach (System.Net.NetworkInformation.UnicastIPAddressInformation unicastAddress in ipInterface.UnicastAddresses)
{
if (unicastAddress.IPv4Mask != null)
{
subnet = unicastAddress.IPv4Mask.ToString();
break;
}
}
}
return subnet;
}
#endregion