程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> 用C#查詢IP所在區段

用C#查詢IP所在區段

編輯:關於C語言

編程語言:C#
類 別:(網絡應用,實用算法)
主要功能:查詢一個IP所有的IP段.
關鍵:從Byte數組到ulong的轉換出來的數字和 IPAddress.Address 返回值的是不一樣的.using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
namespace IPUtility
{
class Program
{
static void Main(string[] args)
{
IPRangeManage irm = new IPRangeManage();
irm.Add(new IPRange("石家莊", "219.148.24.0", "219.148.63.255"));
irm.Add(new IPRange("石家莊", "222.222.0.0", "222.222.63.255"));
irm.Add(new IPRange("唐山", "219.148.64.0", "219.148.79.255"));
irm.Add(new IPRange("保定", "219.148.20.0", "219.148.23.255"));
Console.WriteLine(irm.Search("219.148.56.3").Name);
Console.ReadLine();
}

}
public class IPRange
{
private string _Name = string.Empty;
private ulong _BeginIP = 0;
private ulong _EndIP = Int32.MaxValue;
/**//// <summary>
/// IP段名稱
/// </summary>
public string Name
{
get { return _Name; }
set { _Name = value; }
}
/**//// <summary>
/// ?始IP
/// </summary>
public ulong BeginIP
{
get { return _BeginIP; }
set { _BeginIP = value; }
}
/**//// <summary>
/// ?束IP
/// </summary>
public ulong EndIP
{
get { return _EndIP; }
set { _EndIP = value; }
}

/**//// <summary>
/// 此IP段的范?
/// </summary>
public ulong Range
{
get
{
return EndIP - BeginIP;
}
}
public IPRange(string name, string ipBegin, string ipEnd)
{
this.Name = name;
this.BeginIP = IP2A(ipBegin);
this.EndIP = IP2A(ipEnd);
}

public static ulong IP2A(string ip)
{
byte[] bytes = IPAddress.Parse(ip).GetAddressBytes();
ulong ret = 0;
foreach (byte b in bytes)
{
ret <<= 8;
ret |= b;
}
return ret;
}

public static int Compare(IPRange x, IPRange y)
{
if(x.Range == y.Range)
return 0;
else if(x.Range > y.Range)
return 1;
else return -1;
}
}
public class IPRangeManage
{
public IPRangeManage()
{ }
private List< IPRange> _IPRangeList = new List< IPRange>();
private bool _NeedSort = true;
public void Add(IPRange ipRange)
{
_IPRangeList.Add(ipRange);
_NeedSort = true;
}
private void Sort()
{
if (_NeedSort)
{
_IPRangeList.Sort(new Comparison<IPRange>(IPRange.Compare));
}
}
public IPRange Search(string ipString)
{
ulong ip = IPRange.IP2A(ipString);
this.Sort();
foreach (IPRange ir in _IPRangeList)
{
if (ir.BeginIP <= ip && ir.EndIP >= ip)
{
return ir;
}
}
return null;
}

}


}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved