IP地址解析

时间:2023-03-08 17:24:25
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('[') + ;
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[].Value, )).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 = ;
object Key="";
foreach (Group item in result)
{
if (i == )
{
ht.Add(item.Value, "");
Key = item.Value;
i++;
}
else
{
ht[Key] = item.Value;
i--;
}
}
Console.ReadKey();
}
} }