using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WindowsFormsApp1
{
public class Ipv4
{
#region IPv4 List
/// <summary>
/// 这里填写 CIDR格式IP地址段
/// https://github.com/LisonFan/china_ip_list/blob/master/china_ipv4_list
/// https://www.ipaddressguide.com/cidr
/// </summary>
static string ipv4List = @"";
#endregion
public static bool CheckIpInList(string ip)
{
string[] ipAndMask = ipv4List.Split(new char[] { '\n' });
List<IPv4Data> ips = new List<IPv4Data>();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < ipAndMask.Length; i++)
{
string[] iNm = ipAndMask[i].Split(new char[] { '/' });
if (iNm.Length == 2)
{
IPv4Data ipData = new IPv4Data();
string ipStr = iNm[0];
int mask = int.Parse(iNm[1]);
ipData.IP = IpToUint(ipStr);
ipData.ShortIp = ipData.IP >> (32 - mask);
uint maskUint = uint.MaxValue << (32 - mask);
ipData.MaxIp = ipData.IP | ~maskUint;
ipData.IpBit = Convert.ToString(ipData.IP, 2);
ipData.ShortIpBit = Convert.ToString(ipData.ShortIp, 2);
ipData.MaxIpBit = Convert.ToString(ipData.MaxIp, 2);
ipData.IpBlock = ipAndMask[i];
sb.AppendLine(ipStr);
sb.AppendLine(ipData.ShortIpBit);
sb.AppendLine(ipData.IpBit);
sb.AppendLine(ipData.MaxIpBit);
sb.AppendLine();
ips.Add(ipData);
}
}
uint checkIp = IpToUint(ip);
for (int i = 0; i < ips.Count; i++)
{
IPv4Data ipData = ips[i];
if (checkIp > ipData.IP && checkIp < ipData.MaxIp)
{
return true;
}
}
string show = sb.ToString();
return false;
}
public static uint IpToUint(string ip)
{
string[] ipByte = ip.Split(new char[] { '.' });
uint ip1 = uint.Parse(ipByte[0]) << 24;
uint ip2 = uint.Parse(ipByte[1]) << 16;
uint ip3 = uint.Parse(ipByte[2]) << 8;
uint ip4 = uint.Parse(ipByte[3]);
return ip1 | ip2 | ip3 | ip4;
}
}
public class IPv4Data
{
public string IpBlock { get; set; }
public string MaxIpBit { get; set; }
public string IpBit { get; set; }
public string ShortIpBit { get; set; }//右移掩码的补数位
public uint ShortIp { get; set; }//右移掩码的补数位
public uint IP { get; set; }
public uint MaxIp { get; set; }
}
}