02 Mart 2010 Salı

IP adresinden şehir ve ülkeyi tespit etme (C#)

Girilen IP hakkında detaylı bilgi veren bir servis var (http://ipinfodb.com/ip_query.php?ip=IP) bu servis daha önceden h4ckinger phpde kullandı fakat bende C#da nasıl kullanılır onu açıklayayım :)

Başlamadan önce bi inceliyelim.. http://ipinfodb.com/ip_query.php?ip=209.85.227.104 diye çalıştırdığımızda bize



diye bir xml dosyası döndürüyor şimdi bu xmlyi önce bilgisayarımıza download edip daha sonra ReadXml fonksiyonu ile okuyacağız..


Öncelikle WebClient sınıfını kullanıcağımız için System.Net i eklememiz gerek


using System.Net;

string IP = "209.85.227.104";
DataSet ds = new DataSet();
WebClient wb = new WebClient();
wb.DownloadFile("http://ipinfodb.com/ip_query.php?ip=" + IP, "x.xml");
ds.ReadXml("x.xml");
foreach(DataRow dr in ds.Tables[0].Rows)
{
MessageBox.Show("Ülke : " + dr["CountryName"].ToString());
MessageBox.Show("Şehir : " + dr["City"].ToString());
}


bu şekilde kolonları tek tek çektik istersek hepsini birlikte çekip datagrid e atayabiliriz..

string IP = "209.85.227.104";
DataSet ds = new DataSet();
WebClient wb = new WebClient();
wb.DownloadFile("http://ipinfodb.com/ip_query.php?ip=" + IP, "x.xml");
ds.ReadXml("x.xml");
dataGridView1.DataMember = "Response";
dataGridView1.DataSource = ds;

bu sayede programımızı kullananlar hakkında bilgi edinebiliriz ee peki kullanıcının ipsini nerden bulabiliriz ?

çok basit..

using System.Net;
using System.Text.RegularExpressions;
using System.IO;

//namespacelerini ekliyoruz.


private string source(string siteAddress)
{
string retVal = "";
WebResponse webResponse = null;
try
{
WebRequest webRequest = WebRequest.Create(siteAddress);
webResponse = webRequest.GetResponse();
Stream stream = webResponse.GetResponseStream();
StreamReader streamReader = new StreamReader(stream);
retVal = streamReader.ReadToEnd();
}
catch (WebException)
{
//Error
}
return retVal;
}

kaynak kod için fonksiyonumuzu yazdık..

string src = source("http://whatismyipaddress.com/");
Regex regex = new Regex("Your IP address is (.*?)");
Match ipm = regex.Match(src);
string IP = ipm.Groups[0].ToString();
DataSet ds = new DataSet();
WebClient wb = new WebClient();
wb.DownloadFile("http://ipinfodb.com/ip_query.php?ip=" + IP, "x.xml");
ds.ReadXml("x.xml");
dataGridView1.DataMember = "Response";
dataGridView1.DataSource = ds;


bu kadar basit.. kolay gelsin :)

0 yorum:

Yorum Gönder