C#,asp.net读取yodao提供的ip地址库接口查询IP地址

在编程当中会遇到需要根据IP来源判断IP的详细地址,在国内大多数系统都会采用纯真IP数据库,把IP数据库下载到本地,然后进行调用,像discuz论坛采用的就是此类方法。但是此类方法存在许多缺点:IP数据库文件比较大,如discuz的IP数据库就达到了6M;由于IP每天都会有增加和减少,这就使得下载到本地的IP数据库更新不及时......。

有什么方法可以达到根据IP取IP地址完美方法呢?答案就是使用第三方提供的IP接口

有道(yodao)提供了IP地址查询接口,我们就采用有道(yodao)提供的IP地址查询接口详细讲解,用C#(asp.net)调用。

有道(yodao)提供的接口返回给我们是xml格式的文件,在IE中输入网址:http://www.youdao.com/smartresult-xml/search.s?type=ip&q=59.58.2.171,得到的格式文件就是:

<?xml version="1.0" encoding="gbk" ?>

- <smartresult>

- <product type="ip">

<ip>119.39.90.225</ip>

<location>福建省宁德市 (古田县)电信 </location>

</product>

</smartresult>

我们真正需要只有<location>湖南省 网通</location> 这个,C#(asp.net)调用代码如下:

#region 读取http://www.yodao.com接口IP地址

/// <summary>

/// 读取http://www.yodao.com接口IP地址

/// </summary>

public static string GetstringIpAddress(string strIP)//strIP为IP

{

string sURL = "http://www.youdao.com/smartresult-xml/search.s?type=ip&q="+strIP+"";//youdao的URL

string stringIpAddress = "";

using (XmlReader read = XmlReader.Create(sURL))//获取youdao返回的xml格式文件内容

{

while (read.Read())

{

switch (read.NodeType)

{

case XmlNodeType.Text://取xml格式文件当中的文本内容

if (string.Format("{0}", read.Value).ToString().Trim() != strIP)//youdao返回的xml格式文件内容一个是IP,另一个是IP地址,如果不是IP

那么就是IP地址

{

stringIpAddress=string.Format("{0}", read.Value).ToString().Trim();//赋值

}

break;

//other

}

}

}

return stringIpAddress;

}

#endregion 读取http://www.yodao.com接口IP地址