Using an web service to determine the originating country for an IP address.
More C# Resources
After the tutorial on how to use the Google Search Web Service I’ve got a tutorial on using Web Services which is even simpler.
This time we’ll use a Web Service that enables you to look up the originating country for an IP address.
Information about the sevice is available here.
And the WSDL Schema Location is here.
Now open Microsoft Visual C# .NET and start a new Windows Application project named GeoIP.
Add two textboxes named txtIP and txtCountry and a button named btnCheck.
Here’s the design of the form (I also added two labels):
Now let’s add a Web Reference to the web service. So right click the project in the Solution Explorer window and choose Add Web Reference.
The following URL is the one that leads to the web service: http://www.webservicex.net/geoipservice.asmx?WSDL – so this is what we’ll enter on the Address text box. Press enter to verify the reference and then click Add Reference. After the reference is added, give it a friendlier name: geoip:
Now we code. Unfortunately we don’t have much to code 🙂
public void checkIP(string ip)
{
   // Change cursor to WaitCursor
   this.Cursor = Cursors.WaitCursor;
   // Create new GeoIPService
   geoip.GeoIPService IPServ = new geoip.GeoIPService();
   // Use GetGeoIP method to check the IP
   geoip.GeoIP IPRes = IPServ.GetGeoIP(ip);
   // If ReturnCode is 1, IP was found
   if(IPRes.ReturnCode == 1)
   {
      // Change BackColor to normal
      txtCountry.BackColor = Color.White;
      // Display the name of the country
      txtCountry.Text = IPRes.CountryName.ToString();
   }
   // If IP wasn't found
   else
   {
      // Give a red tint to the TextBox
      txtCountry.BackColor = Color.FromArgb(255, 235, 235);
      // And tell the user it wasn't found
      txtCountry.Text = "IP not found";
   }
   // Cursor back to default
   this.Cursor = Cursors.Default;
}
private void btnCheck_Click(object sender, System.EventArgs e)
{
   // Call checkIP to check the IP in the TextBox
   checkIP(txtIP.Text);
}
Go ahead, try it:
Go ahead, try it:That wasn’t so hard 🙂