Created
February 22, 2017 09:45
-
-
Save code-atom/abf1bf3ccbca392ab967f8ee081b369e to your computer and use it in GitHub Desktop.
Find the IPAddress to Location
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Newtonsoft.Json; | |
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.Linq; | |
using System.Linq.Expressions; | |
using System.Net; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace IpAddressAccess | |
{ | |
public class IPAddressLocation | |
{ | |
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 float latitude { get; set; } | |
public float longitude { get; set; } | |
public int metro_code { get; set; } | |
} | |
class Program | |
{ | |
private static string _defaultCookieValue = "NCUTY"; | |
static void Main(string[] args) | |
{ | |
foreach (var ip in GetIPAddress()) | |
{ | |
var output = _GetCountryCodeFromIP(ip); | |
Console.WriteLine("IpAddress {0}, Country Code: {1}", ip, output); | |
} | |
Console.ReadLine(); | |
} | |
private static string _GetCountryCodeFromIP(string ipaddress) | |
{ | |
try | |
{ | |
string url = "http://freegeoip.net/json/" + ipaddress; | |
WebClient client = new WebClient(); | |
string jsonstring = client.DownloadString(url); | |
var results = JsonConvert.DeserializeObject<IPAddressLocation>(jsonstring); | |
return String.IsNullOrEmpty(results.country_code) ? _defaultCookieValue : results.country_code; | |
} | |
catch (WebException ex) | |
{ | |
return _defaultCookieValue; | |
} | |
} | |
public static IEnumerable<string> GetIPAddress() | |
{ | |
using (StreamReader readFile = new StreamReader("./IPAddress.csv")) | |
{ | |
string line; | |
string[] row; | |
while ((line = readFile.ReadLine()) != null) | |
{ | |
row = line.Split(','); | |
yield return row[0]; | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment