School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Welcome to Dream.In.Code
Become an Expert!

Join 307,112 Programmers for FREE! Get instant access to thousands of experts, tutorials, code snippets, and more! There are 2,009 people online right now. Registration is fast and FREE... Join Now!




Class CountryIP VB/C#

 
Reply to this topicStart new topic

> Class CountryIP VB/C#, Need to know where an IP is from over and over again?

CamoDeveloper
Group Icon



post 5 Aug, 2009 - 10:31 PM
Post #1


Hey, it's me again with another tutorial.

Do you have to check to see where the IP that is viewing your site is from? Or want to block certain countries from viewing pages? Well listen up, because you're going to create your very own class so you don't have to re-write the code every time.

Start by adding a new class to your project. I'm naming mine CountryIP.
CODE

Public Class CountryIP
End Class


Next, Import these four System Namespace's
CODE

Imports System.Net
Imports System.IO
Imports System.Xml
Imports System.Collections.Specialized

Public Class CountryIP
End Class

*Explanation of why we need these*

- System.Net : So we can access and use the HTTPWebRequest/Response Classes
- System.IO : So we can access the StreamReader Class to work with the data retrieved from the web
- System.Xml : So we can work the xml the site sends back
- System.Collections.Specialized : So we can parse the xml for the data we are looking for

Now, the first function I am going to make for this class is IPRequestHelper. This function will handle all of my web requests and responses so I don't have to re-write the code if needed later on down the road. I'm going to set two parameters to pass into this function, one is url and the other is ipAddress.
CODE

Public Function IPRequestHelper(ByVal url As String, ByVal ipAddress As String) As String
End Function


Next we declare a string variable that will combine our url and ipAddress together
CODE

Public Function IPRequestHelper(ByVal url As String, ByVal ipAddress As String) As String
        Dim checkURL As String = url & ipAddress
End Function


Now, we declare our HTTPWebRequest/Response variables to handle the "GET" to the url and retrieve the response
CODE

Public Function IPRequestHelper(ByVal url As String, ByVal ipAddress As String) As String
        Dim checkURL As String = url & ipAddress

        Dim objRequest As HttpWebRequest = CType(WebRequest.Create(url), HttpWebRequest)
        Dim objResponse As HttpWebResponse = CType(objRequest.GetResponse(), HttpWebResponse)
End Function


Then, declare our StreamReader variable to use our ObjResponse and open up a stream and get all of the data it contains. Then we close the stream and dispose of it to free memory. We return our responseRead value
CODE

Public Function IPRequestHelper(ByVal url As String, ByVal ipAddress As String) As String
        Dim checkURL As String = url & ipAddress

        Dim objRequest As HttpWebRequest = CType(WebRequest.Create(url), HttpWebRequest)
        Dim objResponse As HttpWebResponse = CType(objRequest.GetResponse(), HttpWebResponse)

        Dim responseStream As New StreamReader(objResponse.GetResponseStream())
        Dim responseRead As String = responseStream.ReadToEnd()

        responseStream.Close()
        responseStream.Dispose()

        Return responseRead
End Function


Now that we have our helper function, let us create our GetCountryByIP function
CODE

Public Function GetCountryByIP(ByVal ipAddress As String) As String
End Function


We can set our IP variable using the "REMOTE_ADDR" Server Variable. Then we set our response variable based on the results from our IPRequestHelper function.
CODE

Public Function GetCountryByIP(ByVal ipAddress As String) As String
        Dim ipResponse As String = IPRequestHelper("http://ipinfodb.com/ip_query_country.php?ip=", ipAddress)
End Function


Next, we declare our XmlDocument variable which loads the xml returned in the ipResponse variable. Then we tell it which node to select for our base
CODE

Public Function GetCountryByIP(ByVal ipAddress As String) As String
        Dim ipResponse As String = IPRequestHelper("http://ipinfodb.com/ip_query_country.php?ip=", ipAddress)

        Dim ipInfoXML As XmlDocument = New XmlDocument() : ipInfoXML.LoadXml(ipResponse)
        Dim responseXML As XmlNodeList = ipInfoXML.GetElementsByTagName("Response")
End Function


We now declare a NameValueCollection array variable. Then we take the first item of the responseXML data array (Since it will only be one response returned) and add the ChildNode key and value that we want to our NameValueCollections variable. After get the data added to the dataXML variable we declare a string variable the retrieves the very first key of the dataXML. We then return our key value.
CODE

Public Function GetCountryByIP(ByVal ipAddress As String) As String
        Dim ipResponse As String = IPRequestHelper("http://ipinfodb.com/ip_query_country.php?ip=", ipAddress)

        Dim ipInfoXML As XmlDocument = New XmlDocument() : ipInfoXML.LoadXml(ipResponse)
        Dim responseXML As XmlNodeList = ipInfoXML.GetElementsByTagName("Response")

        Dim dataXML As NameValueCollection = New NameValueCollection()

        dataXML.Add(responseXML.Item(0).ChildNodes(2).InnerText, responseXML.Item(0).ChildNodes(2).Value)

        Dim xmlValue As String = dataXML.Keys(0)

        Return xmlValue
End Function


There, your class is all setup and ready to go. If you want to use it you can do :
CODE

Response.Write(CountryIP.GetCountryByIP(Request.ServerVariables("REMOTE_ADDR")))


That will output "US" if you're in the United States, etc.

Below are the full VB and C# Class.

VB
CODE

Imports System.Net
Imports System.IO
Imports System.Xml
Imports System.Collections.Specialized

Public Class CountryIP
    Public Function GetCountryByIP(ByVal ipAddress As String) As String
        Dim ipResponse As String = IPRequestHelper("http://ipinfodb.com/ip_query_country.php?ip=", ipAddress)

        Dim ipInfoXML As XmlDocument = New XmlDocument() : ipInfoXML.LoadXml(ipResponse)
        Dim responseXML As XmlNodeList = ipInfoXML.GetElementsByTagName("Response")

        Dim dataXML As NameValueCollection = New NameValueCollection()

        dataXML.Add(responseXML.Item(0).ChildNodes(2).InnerText, responseXML.Item(0).ChildNodes(2).Value)

        Dim xmlValue As String = dataXML.Keys(0)

        Return xmlValue
    End Function

    Public Function IPRequestHelper(ByVal url As String, ByVal ipAddress As String) As String
        Dim checkURL As String = url & ipAddress

        Dim objRequest As HttpWebRequest = CType(WebRequest.Create(url), HttpWebRequest)
        Dim objResponse As HttpWebResponse = CType(objRequest.GetResponse(), HttpWebResponse)

        Dim responseStream As New StreamReader(objResponse.GetResponseStream())
        Dim responseRead As String = responseStream.ReadToEnd()

        responseStream.Close()
        responseStream.Dispose()

        Return responseRead
    End Function
End Class


C#
CODE

using System.Net;
using System.IO;
using System.Xml;
using System.Collections.Specialized;

public class CountryIP {
    public string GetCountryByIP(string ipAddress) {
      string ipResponse = IPRequestHelper("http://ipinfodb.com/ip_query_country.php?ip=", ipAddress);
      
      XmlDocument ipInfoXML = new XmlDocument();
      ipInfoXML.LoadXml(ipResponse);
      XmlNodeList responseXML = ipInfoXML.GetElementsByTagName("Response");
      
      NameValueCollection dataXML = new NameValueCollection();
      
      dataXML.Add(responseXML.Item(0).ChildNodes(2).InnerText, responseXML.Item(0).ChildNodes(2).Value);
      
      string xmlValue = dataXML.Keys(0);
      
      return xmlValue;
    }
    
    public string IPRequestHelper(string url, string ipAddress) {
      string checkURL = url + ipAddress;
        
      HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
      HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
      
      StreamReader responseStream = new StreamReader(objResponse.GetResponseStream());
      string responseRead = responseStream.ReadToEnd();
      
      responseStream.Close();
      responseStream.Dispose();
      
      return responseRead;
    }
}


Thanks for reading my tutorial! If there is anything I need to explain better or work on feel free to comment!

~Camo

*EDIT* Syntax error - Forgot to add the last parenthesis to the example.

This post has been edited by CamoDeveloper: 7 Aug, 2009 - 07:05 PM
Go to the top of the page
+Quote Post


Register to Make This Ad Go Away!


Fast ReplyReply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 


Lo-Fi Version Time is now: 11/21/09 01:17PM

Live Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month