using System;
03 using System.IO;
04 using System.Net;
05 using System.Text;
06 using System.Web.Script.Serialization;
07
08 namespace IpUtils
09 {
10 public class IpDetail
11 {
12 public String Ret { get; set; }
13
14 public String Start { get; set; }
15
16 public String End { get; set; }
17
18 public String Country { get; set; }
19
20 public String Province { get; set; }
21
22 public String City { get; set; }
23
24 public String District { get; set; }
25
26 public String Isp { get; set; }
27
28 public String Type { get; set; }
29
30 public String Desc { get; set; }
31 }
32
33 public class IpHelper
34 {
35 /// <summary>
36 /// 获取IP地址的详细信息,调用的借口为
37 /// http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip={ip}
38 /// </summary>
39 /// <param name="ipAddress">请求分析得IP地址</param>
40 /// <param name="sourceEncoding">服务器返回的编码类型</param>
41 /// <returns>IpUtils.IpDetail</returns>
42 public static IpDetail Get(String ipAddress,Encoding sourceEncoding)
43 {
44 String ip = string.Empty;
45 if(sourceEncoding==null)
46 sourceEncoding = Encoding.UTF8;
47 using (var receiveStream = WebRequest.Create("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip="+ipAddress).GetResponse().GetResponseStream())
48 {
49 using (var sr = new StreamReader(receiveStream, sourceEncoding))
50 {
51 var readbuffer = new char[256];
52 int n = sr.Read(readbuffer, 0, readbuffer.Length);
53 int realLen = 0;
54 while (n > 0)
55 {
56 realLen = n;
57 n = sr.Read(readbuffer, 0, readbuffer.Length);
58 }
59 ip = sourceEncoding.GetString(sourceEncoding.GetBytes(readbuffer, 0, realLen));
60 }
61 }
62 return !string.IsNullOrEmpty(ip)?new JavaScriptSerializer().Deserialize<IpDetail>(ip):null;
63 }
64 }
65
66 public class EncodingHelper
67 {
68 public static String GetString(Encoding source, Encoding dest, String soureStr)
69 {
70 return dest.GetString(Encoding.Convert(source, dest, source.GetBytes(soureStr)));
71 }
72
73 public static String GetString(Encoding source, Encoding dest, Char[] soureCharArr, int offset, int len)
74 {
75 return dest.GetString(Encoding.Convert(source, dest, source.GetBytes(soureCharArr, offset, len)));
76 }
77 }
78 }