下面这段代码将IP地址转换为地方名称,例如你的IP地址为 “58.24.25.65” 则显示为 “上海徐汇区”
当然转换过程中,需要有数据库,也就是这里适用的数据库是动网论坛最新版本DVBBS8.1提供的数据库,你可以到dvbbs下载那个论坛,然后在data目录下找到
ipaddress数据库文件,其中ip1和ip2对应ip地址的范围
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data.OleDb"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
string Ip =Request.UserHostAddress;
string[] Ip_List = Ip.Split(".".ToCharArray());
string X_Ip = "";
foreach (string ip in Ip_List)
{
string tmp = Convert.ToInt16(ip).ToString("x");
X_Ip += tmp;
}
long num = long.Parse(X_Ip, System.Globalization.NumberStyles.HexNumber);
string aConnStr = "Provider = Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("ipaddress.mdb");
System.Data.OleDb.OleDbConnection con = new System.Data.OleDb.OleDbConnection(aConnStr);
System.Data.OleDb.OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
con.Open();
cmd.CommandText = "select top 1 country,city from dv_address where ip1 <=" + num + " and ip2 >=" + num;
string result = cmd.ExecuteScalar().ToString();
con.Close();
Response.Write(result);
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>