C# 根据IP获取省市

2018-06-22 07:33:55来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折


/// <summary>

        /// 根据IP获取省市

        /// </summary>

        public void GetAddressByIp()

        {

            string ip = "115.193.217.249";

            string PostUrl = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?ip=" + ip;

            string res = GetDataByPost(PostUrl);//该条请求返回的数据为:res=1\t115.193.210.0\t115.194.201.255\t中国\t浙江\t杭州\t电信


            string[] arr = getAreaInfoList(res);

        }


        /// <summary>

        /// Post请求数据

        /// </summary>

        /// <param name="url"></param>

        /// <returns></returns>

        public string GetDataByPost(string url)

        {

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);

            string s = "anything";

            byte[] requestBytes = System.Text.Encoding.ASCII.GetBytes(s);

            req.Method = "POST";

            req.ContentType = "application/x-www-form-urlencoded";

            req.ContentLength = requestBytes.Length;

            Stream requestStream = req.GetRequestStream();

            requestStream.Write(requestBytes, 0, requestBytes.Length);

            requestStream.Close();


            HttpWebResponse res = (HttpWebResponse)req.GetResponse();

            StreamReader sr = new StreamReader(res.GetResponseStream(), System.Text.Encoding.Default);

            string backstr = sr.ReadToEnd();

            sr.Close();

            res.Close();

            return backstr;

        }


        /// <summary>

        /// 处理所要的数据

        /// </summary>

        /// <param name="ip"></param>

        /// <returns></returns>

        public static string[] getAreaInfoList(string ipData)

        {

            //1\t115.193.210.0\t115.194.201.255\t中国\t浙江\t杭州\t电信

            string[] areaArr = new string[10];

            string[] newAreaArr = new string[2];

            try

            {

                //取所要的数据,这里只取省市

                areaArr = ipData.Split('\t');

                newAreaArr[0] = areaArr[4];//省

                newAreaArr[1] = areaArr[5];//市

            }

            catch (Exception e)

            {

                // TODO: handle exception

            }

            return newAreaArr;

        }

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:一个人开发的.Net版轻量级博客,欢迎吐槽,互相学习!

下一篇:Redis两种持久化方式(RDB&amp;AOF)