« Home | Error Handling in Web.Config » | Handling Application_Error Method » | Error Handling in .net 3.5 » | Using LINQ in String Collections » | SQL in .net Using LINQ » | Querying the DataTable in .Net » | Converting DataView into DataTable » | Deleting TFS Project »

Getting IP Address and ISP name of our Web Page Visitors

We all know how to get the IP address of the user accessing our website.

In .net , we can achieve this by using the Dns.GetHostByName() method.

What if the case, that we need the ISP(Interner Service Provider) name of that IP too.

Code for finding the IP address goes below.


string strHostName = Dns.GetHostName();
IPHostEntry ipEntry = Dns.GetHostByName(strHostName);
IPAddress[] addr = ipEntry.AddressList;
string strIp = addr[0].ToString();


Now we got the IP address of our web page visitor.

Lets find the ISP NAME of that visitor.

For this , first we need to know the Regional Internet Registry that allocates IP and AS numbers.

If the IP address is from the ASIA PACIFIC REGION,we need to query the APNIC.NET, who holds the IP addresses list for ASIA PACIFIC.

And if the IP address is from the American region, we need to query the ARIN.NET(American Registry for Internet Numbers).

For other regions pls. google and find out the respective registry.

Lets assume, the visitor is from the asia region, we got the IP address from the steps above and now lets find out the ISP name of that visitor.

using System.Net.Sockets;
using System.IO;

string ipaddress = ""; // ip address goes here
string strResponse = "";
NetworkStream stream;
StreamReader reader;
StreamWriter writer;
TcpClient tcpc;
tcpc = new TcpClient();
tcpc.Connect("whois.apnic.net", 43);
stream = tcpc.GetStream(); // Get refrence to opened Network stream
reader = new StreamReader(stream); // Lets assign reader to stream
writer = new StreamWriter(stream); // lets assign writer to stream
writer.WriteLine(ipaddress);
writer.Flush();
while (!reader.EndOfStream)
{
strResponse += reader.ReadLine() + Environment.NewLine;
}
stream.Close();


Now you got the response stream in strResponse, you can iterate through the response , to get the ISP NAME.

The same method is applicable to get the ISP in American Region.

Instead of "whois.apnic.net" , we need to use "whois.arin.net".

We can manipulate the code, in several ways to get the different infomation about an IP address.


Happy coding...

Labels: , , , , , ,

Post a Comment