C# :: Aufgabe #158 :: Lösung #2
4 Lösungen

#158
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 ;)
#2

von daniel59 (4260 Punkte)
- 04.01.2017 um 12:04 Uhr

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); } } }
Kommentare:
Für diese Lösung gibt es noch keinen Kommentar
Seite 1 von 0
1