Recently, during the development project, you need to obtain the IP address area used for statistical analysis. After some materials, I wrote a test program and quickly completed this function.
Now, let's share my implementation methods. If you have better implementations, please feel free to propose them.
First, I found a common WebService, http://webservice.webxml.com.cn/webservices/ipaddresssearchwebservice.asmx.
Call the getCountryCityByIp method to obtain the region address of the specific IP address. This WebService is described as follows:
GetCountryCityByIp
Enter an IP address to query country, city, owner, and other information. China if the country is not specified
Input parameter: IP address (automatically replaced ". "."), Return data: A one-dimensional String array String (1), String (0) = IP address; String (1) = query result or prompt
The next step is to obtain the IP address of the user's current computer. The specific implementation method is as follows:
/// <Summary>
/// Obtain the IP address of the Local Machine
/// </Summary>
/// <Returns> </returns>
Private string GetConnectNetAddress ()
{
String strUrl = "http://www.ip138.com/ip2city.asp"; // obtain the IP Address URL
Uri uri = new Uri (strUrl );
WebRequest webreq = WebRequest. Create (uri );
Stream s = webreq. GetResponse (). GetResponseStream ();
StreamReader sr = new StreamReader (s, Encoding. Default );
String all = sr. ReadToEnd (); // read the data format returned by the website: your IP address is [x. x]
Int I = all. IndexOf ("[") + 1;
String tempip = all. Substring (I, 15 );
String ip = tempip. Replace ("]", ""). Replace ("", ""). Replace ("<","");
Return ip;
}
This method is.
Of course, if the website has changed its domain name or does not exist that day, this method cannot be used.
The next thing is very simple. Add the preceding webservice to the project, and then call this webservice to obtain the Internet access area.
The specific implementation is as follows:
/// <Summary>
/// Region where the Internet IP address is obtained
/// </Summary>
/// <Returns> </returns>
Private string GetConnectNetAddressArea ()
{
String strIP = GetConnectNetAddress ();
IpAddressSearchWebService webService = new IpAddressSearchWebService ();
String [] strArea = webService. getCountryCityByIp (strIP );
Return strArea [1];
}
In this way, the region where the IP address is queried by the user is successfully obtained.
From weizhiai12's column