技术资讯   > 技术文章 > 根据IP获得所在地址(本站原创)
[发表时间: 2008-10-11 04:56 ]

地址库可以去网上去下载

程序代码:

 public string getdz(string ipd)
    {
        string str1 = string.Empty;
        string str2 = string.Empty;
        string str3 = string.Empty;
        string str4 = string.Empty;
        string str = ipd.Substring(0, 2);
        string dz = string.Empty;
        if (Convert.ToInt32(str) > 0)
        {
            if (ipd == "127.0.0.1")
            {
                ipd = "192.168.0.1";
               // dz = "本机IP";
            }
            str1 = ipd.Substring(0, ipd.IndexOf("."));
            ipd = ipd.Substring(ipd.IndexOf(".") + 1);
            str2 = ipd.Substring(0, ipd.IndexOf("."));
            ipd = ipd.Substring(ipd.IndexOf(".") + 1);
            str3 = ipd.Substring(0, ipd.IndexOf("."));
            str4 = ipd.Substring(ipd.IndexOf(".") + 1);
            if (Convert.ToInt32(str1) == 0 || Convert.ToInt32(str2) == 0 || Convert.ToInt32(str3) == 0 || Convert.ToInt32(str4) == 0)
            {
                dz = "本机IP";
            }
            else
            {
                int num = Convert.ToInt32(str1) * 256 * 256 * 256 + Convert.ToInt32(str2) * 256 * 256 + Convert.ToInt32(str3) * 256 + Convert.ToInt32(str4) - 1;
                OleDbConnection connection = new OleDbConnection(ss.DAL.ConnectionString.GetConnectionString());
                connection.Open();
                OleDbCommand command = new OleDbCommand("select * from ip  where StartIP <=" + num + " and EndIP >=" + num + "", connection);
               
                OleDbDataReader odr = command.ExecuteReader(CommandBehavior.CloseConnection);
              
                if (odr.Read())
                {
                    dz = odr["addr"].ToString();
                }
                else
                {
                    dz = "";
                }

            }

        }
        else
        {
            dz = "";
        }
        return dz;
    }