根据IP地址显示城市拼音
可以获取客户端的IP地址,浏览者的所在城市,城市的全拼,二级域名。
其数据来源于mdb数据库,里面包含两个表:city_py和ip_address,其中city_py可以应用于根据拼音首字母检索城市。
关键代码:
// 获取客户端所在城市,省份,跳转域名
public string[] GetCustomCity()
{
string Ip = GetClientIP();
string[] ipcontent = new string[3];
try
{
long ipint = IPtoNum(Ip);
OleDbConnection oleconn = new OleDbConnection();
oleconn.ConnectionString = CONNSTRING;
OleDbCommand OleCommand = new OleDbCommand();
OleCommand.Connection = oleconn;
OleCommand.CommandText = COMMANDTEXT + ipint.ToString() + ">=ip1 and " + ipint.ToString() + "<=ip2 order by id desc";
oleconn.Open();
OleDbDataReader reader = OleCommand.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
ipcontent[0] = reader["city"].ToString();
ipcontent[1] = reader["province"].ToString();
}
else
{
ipcontent[0] = "";
ipcontent[1] = "";
}
oleconn.Close();
OleCommand.CommandText = selectcityname + "'" + ipcontent[0].ToString() + "'";
oleconn.Open();
reader = OleCommand.ExecuteReader();
if (reader.Read())
{
ipcontent[2] = reader["pinyin"].ToString();
}
else
{
ipcontent[2] = ":该客户端的IP地址信息在数据库中没有找到相关信息";
}
}
catch (Exception ex)
{
ipcontent[0] = ex.Message.ToString();
ipcontent[1] = ex.Source.ToString();
ipcontent[2] = ex.ToString();
}
return ipcontent;
}
//将IP 地址转化为数字
public long IPtoNum(string Ip)
{
string[] stringip = new string[4];
stringip = Ip.Split('.');
long ipnum = Convert.ToInt64((stringip[0])) * 16777216 + Convert.ToInt64(stringip[1]) * 65536 + Convert.ToInt64(stringip[2]) * 256 + Convert.ToInt64(stringip[3]);
return ipnum;
}
//获取客户端的ip地址
public string GetClientIP()
{
string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (null == result || result == String.Empty)
{
result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
if (null == result || result == String.Empty)
{
result = HttpContext.Current.Request.UserHostAddress;
}
return result;
}
运行效果图:
演示代码下载地址: