using System; namespace CcdodoIP { public class IPInfo { private int _id = 0; private double _StartIPInt = 0; private double _EndIPInt = 0; private string _Address = "数据读取失败"; // public int id { get { return _id; } set { _id = value; } } /// <summary> /// double型起始IP /// </summary> public double StartIPInt { get { return _StartIPInt; } set { _StartIPInt = value; } } /// <summary> /// double型结束IP /// </summary> public double EndIPInt { get { return _EndIPInt; } set { _EndIPInt = value; } } /// <summary> /// 地址 /// </summary> public string Address { get { return _Address; } set { _Address = value; } } // } } //主要代码如下: using System; using System.Text; using System.Data; using System.Data.OleDb; using System.Collections; using System.Configuration; using System.Collections.Generic; namespace CcdodoIP { public class IPFactory { #region private string DBName = ConfigurationManager.AppSettings.Get("DBName").ToString(); private string DBDriver = ConfigurationManager.AppSettings.Get("DBDriver").ToString(); private string connectionString { get { return this.DBDriver + System.Web.HttpContext.Current.Server.MapPath("~/" + this.DBName); } } #endregion // #region 判断是否IP地址 private bool IsIP(string str) { string reg = @"/d{1,3}/./d{1,3}/./d{1,3}/./d{1,3}"; return new System.Text.RegularExpressions.Regex(reg).IsMatch(str); } #endregion // #region 解析IP private string[] SplitIP(string UserIP) { return UserIP.Split(".".ToCharArray()); } #endregion // #region IP转换为数字 public double IPToInt(string IP) { double result = 0; if (this.IsIP(IP)) { string[] IPArr = this.SplitIP(IP); result = Convert.ToInt32(IPArr[0]) * 256L * 256L * 256L + Convert.ToInt32(IPArr[1]) * 256L * 256L + Convert.ToInt32(IPArr[2]) * 256L + Convert.ToInt32(IPArr[3]); } return result; } #endregion // #region 得到指定IP所在区域 /// <summary> /// 得到指定IP所在区域 /// </summary> /// <param name="sql"></param> /// <returns></returns> public IPInfo GetIPInfo(string UserIP) { IPInfo Info = new IPInfo(); try { using (OleDbConnection Conn = new OleDbConnection(this.connectionString)) { if (Conn.State != ConnectionState.Open) Conn.Open(); double IPInt = this.IPToInt(UserIP); OleDbCommand comm = new OleDbCommand("select top 1 * from [IPConfig] where " + IPInt + " between [StartIPInt]-1 and [EndIPInt]+1", Conn); OleDbDataReader dr = comm.ExecuteReader(); while (dr.Read()) { Info.id = Convert.ToInt32(dr["id"]); Info.StartIPInt = (double)(dr["StartIPInt"]); Info.EndIPInt = (double)(dr["EndIPInt"]); Info.Address = dr["Address"].ToString(); } dr.Dispose(); Conn.Close(); } } catch (Exception ex) { System.Web.HttpContext.Current.Response.Write(ex.ToString()); } return Info; } #endregion // } // }