IP地址解析

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Text.RegularExpressions;
using System.Collections;

namespace getipaddress
{
    class Program
    {
        static void Main(string[] args)
        {
            WebClient wc = new WebClient();
            string html = wc.DownloadString("http://iframe.ip138.com/ic.asp");//获取本机外网IP
            int iBegin = html.IndexOf('[') + 1;
            int iEnd = html.IndexOf(']');
            string strIP = html.Substring(iBegin, iEnd - iBegin);

            html = wc.DownloadString(string.Format("http://ip.taobao.com/service/getIpInfo.php?ip={0}",strIP));//获得IP地址对应的信息
            html = ConvertUnicode2Chinese(html);
            Console.WriteLine(html);
            Hashtable ht = new Hashtable();
            GetInfo(html,ht);

        }
        /// <summary>
        /// 将编码转换成字符
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        private static string ConvertUnicode2Chinese(string result)
        {
            Regex reg = new Regex(@"(?i)\\[uU]([0-9a-f]{4})", RegexOptions.IgnoreCase | RegexOptions.Singleline);
            return reg.Replace(result,delegate(Match m){ return ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString(); });
        }

        /// <summary>
        /// 将获得的JSON数据存放在Hashtable中
        /// </summary>
        /// <param name="source"></param>
        /// <param name="ht"></param>
        private static void GetInfo(string source,Hashtable ht)
        {
            Regex reg = new Regex("(?<=\")\\w*(?=\")|(?<=\")(\\d{1,3}\\.){3}\\d{1,3}(?=\")|(?<=\")-\\d*(?=\")");
            MatchCollection result = reg.Matches(source);
            int i = 0;
            object Key="";
            foreach (Group item in result)
            {
                if (i == 0)
                {
                    ht.Add(item.Value, "");
                    Key = item.Value;
                    i++;
                }
                else
                {
                    ht[Key] = item.Value;
                    i--;
                }
            }
            Console.ReadKey();
        }
    }

}

 

posted on 2014-04-14 10:06  空空空  阅读(282)  评论(0编辑  收藏  举报

导航