C# :: Aufgabe #158
4 Lösungen

Standort einer beliebigen Ip-Adresse
Anfänger - C#
von ZRX88
- 30.12.2016 um 13:04 Uhr
In Python Aufgabe 101 ( https://trainyourprogrammer.de/python-101-ermitteln-der-ip-klasse.html)
war die Aufgabenstellung für die eingegebene IP die Klasse zu bestimmen.
Viel spannender ist ( aus meiner Sicht) der Standort des Servers:
Nutzt die API https://freegeoip.net/ um den Standort der eingebenen Ip-Adresse ausgeben wird.
Beispiel:
Eingabe = 66.249.66.1
Ausgabe = Die Ip 66.249.66.1 befindet sich in dem Land US in der Stadt Mountain View, die Geo Koordinaten sind 37.4192,-122.0574
p.s. Die Beispiel Ip ist die Ip des Google Bots ;)
war die Aufgabenstellung für die eingegebene IP die Klasse zu bestimmen.
Viel spannender ist ( aus meiner Sicht) der Standort des Servers:
Nutzt die API https://freegeoip.net/ um den Standort der eingebenen Ip-Adresse ausgeben wird.
Beispiel:
Eingabe = 66.249.66.1
Ausgabe = Die Ip 66.249.66.1 befindet sich in dem Land US in der Stadt Mountain View, die Geo Koordinaten sind 37.4192,-122.0574
p.s. Die Beispiel Ip ist die Ip des Google Bots ;)
Lösungen:

using System; using System.Globalization; using System.IO; using System.Net; using System.Xml; namespace IpStandort { class Program { static LocationStrategy LocStrat = new XmlLocation(); static void Main() { Console.Write("IP oder Hostname>"); string input = Console.ReadLine(); Location Location = LocStrat.GetLocation(input); string format = "Die Ip {0} befindet sich in dem Land {1} in der Stadt {2}, die Geo Koordinaten sind {3:0.####}, {4:0.####}"; object[] arg = new object[] { Location.IP, Location.CountryCode, Location.City, Location.Latitude, Location.Longitude, }; Console.WriteLine(format, arg); Console.ReadKey(true); } } interface LocationStrategy { Location GetLocation(string IP_or_hostname); } class XmlLocation : LocationStrategy { public Location GetLocation(string IP_or_hostname) { // Xml manuell holen anstatt mit XmlDocument.Load da dieses unangenehm lange nach einem Proxy sucht. HttpWebRequest Request = WebRequest.CreateHttp("http://freegeoip.net/xml/" + IP_or_hostname) as HttpWebRequest; Request.Proxy = null; string xmlString = ""; using(WebResponse Response = Request.GetResponse()) { using(Stream st = Response.GetResponseStream()) { using(StreamReader sr = new StreamReader(st)) { xmlString = sr.ReadToEnd(); } } } XmlDocument Xml = new XmlDocument(); Xml.LoadXml(xmlString); return Location.FromXml(Xml); } } // Auf Implementierung von Json und Csv (Aufblähung/Fleißarbeit) verzichtet. class JsonLocation : LocationStrategy { public Location GetLocation(string IP_or_hostname) { throw new NotImplementedException(); } } class CsvLocation : LocationStrategy { public Location GetLocation(string IP_or_hostname) { throw new NotImplementedException(); } } class Location { IPAddress _ip; string _countryCode, _countryName, _regionCode, _regionName, _city, _zipCode, _timeZone; float _latitude, _longitude; int _metroCode; public IPAddress IP { get { return _ip; } } public string CountryCode { get { return _countryCode; } } public string CountryName { get { return _countryName; } } public string RegionCoe { get { return _regionCode; } } public string RegionName { get { return _regionName; } } public string City { get { return _city; } } public string ZipCode { get { return _zipCode; } } public string TimeZone { get { return _timeZone; } } public float Latitude { get { return _latitude; } } public float Longitude { get { return _longitude; } } public int MetroCode { get { return _metroCode; } } private Location() { } static public Location FromXml(XmlDocument Xml) { Location Loc = new Location(); XmlNode Root = Xml.SelectSingleNode("Response"); IFormatProvider enUS = new CultureInfo("en-US"); Loc._ip = IPAddress.Parse(Root.SelectSingleNode("IP").InnerText); Loc._countryCode = Root.SelectSingleNode("CountryCode").InnerText; Loc._countryName = Root.SelectSingleNode("CountryName").InnerText; Loc._regionCode = Root.SelectSingleNode("RegionCode").InnerText; Loc._regionName = Root.SelectSingleNode("RegionName").InnerText; Loc._city = Root.SelectSingleNode("City").InnerText; Loc._zipCode = Root.SelectSingleNode("ZipCode").InnerText; Loc._timeZone = Root.SelectSingleNode("TimeZone").InnerText; Loc._latitude = Convert.ToSingle(Root.SelectSingleNode("Latitude").InnerText, enUS); Loc._longitude = Convert.ToSingle(Root.SelectSingleNode("Longitude").InnerText, enUS); Loc._metroCode = Convert.ToInt32(Root.SelectSingleNode("MetroCode").InnerText); return Loc; } static public Location FromJson(string json) { throw new NotImplementedException(); } static public Location FromCsv(string csv) { throw new NotImplementedException(); } } }

using System; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Xml.Linq; namespace ConsoleIPServerLocation { class Program { static void Main(string[] args) { Console.Write("IP-Adresse oder URL: "); string ip = Console.ReadLine(); var location = IPLocation.GetIPLocation(ip); Console.WriteLine(location); Console.ReadLine(); } } class IPLocation { const string address = "http://freegeoip.net/xml/{0}"; static readonly PropertyInfo[] infos = typeof(IPLocation).GetProperties(); static readonly Type Int32Type = typeof(int); static readonly Type DoubleType = typeof(double); static readonly Type StringType = typeof(string); public string IP { get; set; } public string CountryCode { get; set; } public string CountryName { get; set; } public string RegionCode { get; set; } public string RegionName { get; set; } public string City { get; set; } public string ZipCode { get; set; } public string TimeZone { get; set; } public string Latitude { get; set; } public string Longitude { get; set; } public string MetroCode { get; set; } public static IPLocation GetIPLocation(string ip) { IPLocation loc = new IPLocation(); WebClient client = new WebClient(); string xml = client.DownloadString(string.Format(address, ip)); XDocument doc = XDocument.Load(new StringReader(xml)); var elements = doc.Elements().First().Elements(); foreach (var el in elements) { PropertyInfo set = infos.First(a => a.Name == el.Name); set.SetValue(loc, el.Value, null); } return loc; } public override string ToString() { return string.Format("IP: {0}, Lat: {1}, Lon: {2}", IP, Latitude, Longitude); } } }

using System; using System.IO; using System.Net; using System.Windows.Forms; namespace A158_IP_Locator { public partial class frmMain : Form { public frmMain() { InitializeComponent(); } /// <summary> /// Ermittelt den Standort des Server/Client mit der angegebenen IP-Adresse /// </summary> /// <param name="adress">Die IP-Adresse des Server/Client</param> private void CheckAdress(string adress) { //Eingabe prüfen IPAddress ip; if (!IPAddress.TryParse(adress, out ip)) { MessageBox.Show(this, "Sie müssen eine gültige IP-Adresse im Format xxx.xxx.xxx.xxx eingeben", "Ungültige Eingabe", MessageBoxButtons.OK, MessageBoxIcon.Stop); return; } string req = string.Format("http://freegeoip.net/csv/{0}", adress); Uri uri = new Uri(req); WebRequest request = WebRequest.Create(uri); WebResponse response = request.GetResponse(); StreamReader srResponseStream = new StreamReader(response.GetResponseStream()); string answer = srResponseStream.ReadToEnd(); string[] ipInfo = answer.Split(','); string result = string.Format("IP-Adresse:\t{0}\nLänderkürzel:\t{1}\nLand:\t\t{2}\nStadt:\t\t{5}\n\nGeo-Koordinaten\nLängengrad:\t{8}\nBreitengrad:\t{9}", ipInfo); rtbResult.Text = result; } private void btnCheck_Click(object sender, EventArgs e) { CheckAdress(tbAdress.Text.Trim()); } } }

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; using System.Net; using System.IO; namespace ConsoleApplication3 { class Program { static void Main(string[] args) { Console.WriteLine("Geben Sie eine IP-Adresse oder Web-Adresse ein:"); locationResult location = getLocationByIP(Console.ReadLine()); if(location.Equals(new locationResult()) == false) { Console.WriteLine(String.Format("Die Ip {0} befindet sich in dem Land {1} in der Stadt {2}, die Geo Koordinaten sind {3},{4}",location.ip,location.country_code,location.city,location.longitude,location.latitude)); } Console.ReadLine(); } public static locationResult getLocationByIP(string ip) { try { WebRequest request = WebRequest.Create(String.Format("https://freegeoip.net/json/{0}", ip)); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); string responseFromServer = reader.ReadToEnd(); reader.Close(); dataStream.Close(); response.Close(); return Newtonsoft.Json.JsonConvert.DeserializeObject<locationResult>(responseFromServer); } catch(Exception ex) { Console.WriteLine("Es ist ein Fehler aufgetreten: " + ex.Message); return new locationResult(); } } } public class locationResult { public string ip { get; set; } public string country_code { get; set; } public string country_name { get; set; } public string region_code { get; set; } public string region_name { get; set; } public string city { get; set; } public string zip_code { get; set; } public string time_zone { get; set; } public double latitude { get; set; } public double longitude { get; set; } public int metro_code { get; set; } } }