c# ip内外网判断

Posted Mr. Zhang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c# ip内外网判断相关的知识,希望对你有一定的参考价值。

/// <summary>
/// 判断IP地址是否为内网IP地址
/// </summary>
/// <param name="ipAddress">IP地址字符串</param>
/// <returns></returns>
public static bool IsInnerIP(String ipAddress)
{
bool isInnerIp = false;
long ipNum = GetIpNum(ipAddress);
/**
私有IP:A类 10.0.0.0-10.255.255.255
B类 172.16.0.0-172.31.255.255
C类 192.168.0.0-192.168.255.255
当然,还有127这个网段是环回地址
**/
long aBegin = GetIpNum("10.0.0.0");
long aEnd = GetIpNum("10.255.255.255");
long bBegin = GetIpNum("172.16.0.0");
long bEnd = GetIpNum("172.31.255.255");
long cBegin = GetIpNum("192.168.0.0");
long cEnd = GetIpNum("192.168.255.255");
isInnerIp = IsInner(ipNum, aBegin, aEnd) || IsInner(ipNum, bBegin, bEnd) || IsInner(ipNum, cBegin, cEnd) || ipAddress.Equals("127.0.0.1");
return isInnerIp;
}
/// <summary>
/// 把IP地址转换为Long型数字
/// </summary>
/// <param name="ipAddress">IP地址字符串</param>
/// <returns></returns>
private static long GetIpNum(String ipAddress)
{
String[] ip = ipAddress.Split(‘.‘);
long a = int.Parse(ip[0]);
long b = int.Parse(ip[1]);
long c = int.Parse(ip[2]);
long d = int.Parse(ip[3]);

long ipNum = a * 256 * 256 * 256 + b * 256 * 256 + c * 256 + d;
return ipNum;
}
/// <summary>
/// 判断用户IP地址转换为Long型后是否在内网IP地址所在范围
/// </summary>
/// <param name="userIp"></param>
/// <param name="begin"></param>
/// <param name="end"></param>
/// <returns></returns>
private static bool IsInner(long userIp, long begin, long end)
{
return (userIp >= begin) && (userIp <= end);
}

以上是关于c# ip内外网判断的主要内容,如果未能解决你的问题,请参考以下文章

iOS 获取内外网ip

内外网通过公网IP访问DMZ主机

判断内外网环境

获取本机的内外网ip

想双网卡同时上内外网,内外网都具有各自的网关和DNS,如何设置

如何同时上内外网