第一步,首先把數據導入到數據庫,可用cmd命令執行。
1>.在網上下載ipinfodb_one_table_full.sql文件,然後執行cmd命令:
osql -S . -U sunny -P sunny -d IPDB -i ip_group_city.sql
(注:由於文件很大,不能一次性執行,所以需要分成很多小份來操作,osql ? 可查看相關的命令,這裏用到連接數據庫的服務,用戶名,密碼,數據庫,文件。文件存放路徑:C:\DB\IPDB--SQL)
第二步,使用vs展現一個頁面,在後臺寫方法
需要一個文本框輸入IP,一個按鈕查詢,和顯示相關城市信息的lable。爲了方便其他地方調用,把所有操作代碼封裝在方法裏。實現思路:方法是bool類型的,需要返回值,有兩個參數:接收IP,輸出城市。計算IP的方式:
ipnum = 16777216*w + 65536*x + 256*y + z 。IP地址格式一般如:210.75.17.50,所以要使用 Split 分割,把IP地址拆分成4個數據並參與計算。把涉及到的5個城市用一個數組存儲,然後判斷是否和數據庫得到的城市相等,從而知道IP地址所在的城市是否在5個城市內,是則返回true,否則返回false.具體方法如下:
public bool IsExitCityByIP(string ip,out string city)
{
string[] ips = ip.Split('.');
double ipNum = Convert.ToDouble(ips[0]) * 16777216 + Convert.ToDouble(ips[1]) * 65536 + Convert.ToDouble(ips[2]) * 256 + Convert.ToDouble(ips[3]);
string[] cityName = { "Shenzhen", "Shanghai", "Guangzhou", "Hong Kong" };
IPGroupCity c = GetAddressByIPNum(ipNum);
city = c.City.ToString();
if (city != null)計算
{
for (int i = 0; i < cityName.Length; i++)
{
if (cityName[i].Equals(city))
{
lblAddress.Text = "您查詢的IP:" + txtIP.Text + "<br>IP地址位置:" + c.Country_name + "--" + city;
return true;
}
else if (cityName[i].Equals(c.Country_name))
{
lblAddress.Text = "您查詢的IP:" + txtIP.Text + "<br>IP地址位置:" + c.Country_name + "--" + city;
return true;
}
}
lblAddress.Text = "您查詢的IP:" + txtIP.Text + "<br>IP地址位置:" + c.Country_name + "--" + city + "! 您沒有在OpenRice所涉足的五個城市內 ";
return false;
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('您輸入的IP沒有相關記錄')", true);
return false;
}
}