Skip to content

Instantly share code, notes, and snippets.

@neo125874
Last active August 11, 2016 03:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neo125874/547e49eb8bec80fef8292e6e4ff33776 to your computer and use it in GitHub Desktop.
Save neo125874/547e49eb8bec80fef8292e6e4ff33776 to your computer and use it in GitHub Desktop.
get the public ip, search the ip location, and retrieve the google nearby result
public class GetGeoLocation
{
public PlacesApiQueryResponse GetGNBSresult(string querystring) {
byte[] bResult = null;
PlacesApiQueryResponse result = null;
using (WebClient wc = new WebClient())
{
bResult = wc.DownloadData(querystring);
string jsonstring = Encoding.UTF8.GetString(bResult);
result = JsonConvert.DeserializeObject<PlacesApiQueryResponse>(jsonstring);
}
return result;
}
public string GetQueryString(object obj)
{
var properties = from p in obj.GetType().GetProperties()
where p.GetValue(obj, null) != null
select p.Name + "=" + HttpUtility.UrlEncode(p.GetValue(obj, null).ToString());
return string.Join("&", properties.ToArray());
}
public IPData GetIPGeoLocation(string IP)
{
Console.WriteLine("ip input: " + IP);
WebClient client = new WebClient();
// Make an api call and get response.
try
{
string response = client.DownloadString("http://ip-api.com/json/" + IP);
//Deserialize response JSON
IPData ipdata = JsonConvert.DeserializeObject<IPData>(response);
if (ipdata.status == "fail")
{
throw new Exception("Invalid IP");
}
return ipdata;
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Get computer INTERNET address like 93.136.91.7
/// </summary>
/// <returns></returns>
public string GetComputer_InternetIP()
{
string ipAddress;
using (WebClient wc = new WebClient())
{
ipAddress = wc.DownloadString("http://icanhazip.com/");
}
return ipAddress;
//// check IP using DynDNS's service
//WebRequest request = WebRequest.Create("http://checkip.dyndns.org");
//// IMPORTANT: set Proxy to null, to drastically INCREASE the speed of request
//request.Proxy = null;
//WebResponse response = request.GetResponse();
//StreamReader stream = new StreamReader(response.GetResponseStream());
//// read complete response
//string ipAddress = stream.ReadToEnd();
//// replace everything and keep only IP
//return ipAddress.
// Replace("<html><head><title>Current IP Check</title></head><body>Current IP Address: ", string.Empty).
// Replace("</body></html>", string.Empty);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment