Asp.net根据IP显示省市拼音源码

根据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;
    }


运行效果图:

 

演示代码下载地址:

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值