Development Tip

IP 주소로 사용자 위치 가져 오기

yourdevel 2020. 11. 1. 18:48
반응형

IP 주소로 사용자 위치 가져 오기


C #으로 작성된 ASP.NET 웹 사이트가 있습니다.

이 사이트에서 사용자의 위치에 따라 시작 페이지를 자동으로 표시해야합니다.

사용자의 IP 주소를 기반으로 사용자의 도시 이름을 얻을 수 있습니까?


ipdata.co 와 같은 IP 주소 기반 역 지오 코딩 API가 필요합니다 . 사용 가능한 옵션이 많이 있다고 확신합니다.

그러나 사용자가이를 재정의하도록 허용 할 수 있습니다. 예를 들어, IP 주소를 다른 국가에있는 것처럼 보이게 만드는 기업 VPN에있을 수 있습니다 .


http://ipinfo.io를 사용 하세요 . 하루에 1000 건 이상의 요청을하는 경우 비용을 지불해야합니다.

아래 코드에는 Json.NET 패키지 가 필요합니다 .

 public static string GetUserCountryByIp(string ip)
        {
            IpInfo ipInfo = new IpInfo();
            try
            {
                string info = new WebClient().DownloadString("http://ipinfo.io/" + ip);
                ipInfo = JsonConvert.DeserializeObject<IpInfo>(info);
                RegionInfo myRI1 = new RegionInfo(ipInfo.Country);
                ipInfo.Country = myRI1.EnglishName;
            }
            catch (Exception)
            {
                ipInfo.Country = null;
            }

            return ipInfo.Country;
        }

그리고 내가 사용한 IpInfo 클래스 :

public class IpInfo
    {

    [JsonProperty("ip")]
    public string Ip { get; set; }

    [JsonProperty("hostname")]
    public string Hostname { get; set; }

    [JsonProperty("city")]
    public string City { get; set; }

    [JsonProperty("region")]
    public string Region { get; set; }

    [JsonProperty("country")]
    public string Country { get; set; }

    [JsonProperty("loc")]
    public string Loc { get; set; }

    [JsonProperty("org")]
    public string Org { get; set; }

    [JsonProperty("postal")]
    public string Postal { get; set; }
}

IPInfoDB에는 IP 주소를 기반으로 위치를 찾기 위해 호출 할 수 있는 API 가 있습니다.

"City Precision"의 경우 다음과 같이 호출합니다 (무료 API 키를 받으려면 등록해야합니다).

 http://api.ipinfodb.com/v2/ip_query.php?key=<your_api_key>&ip=74.125.45.100&timezone=false

다음 은 API를 호출하는 방법을 보여주는 VB 및 C # 의 예 입니다.


다음 코드는 나를 위해 일합니다.

업데이트

무료 API 요청 (json base) IpStack을 호출하고 있습니다.

    public static string CityStateCountByIp(string IP)
    {
      //var url = "http://freegeoip.net/json/" + IP;
      //var url = "http://freegeoip.net/json/" + IP;
        string url = "http://api.ipstack.com/" + IP + "?access_key=[KEY]";
        var request = System.Net.WebRequest.Create(url);

         using (WebResponse wrs = request.GetResponse())
         using (Stream stream = wrs.GetResponseStream())
         using (StreamReader reader = new StreamReader(stream))
         {
          string json = reader.ReadToEnd();
          var obj = JObject.Parse(json);
            string City = (string)obj["city"];
            string Country = (string)obj["region_name"];                    
            string CountryCode = (string)obj["country_code"];

           return (CountryCode + " - " + Country +"," + City);
           }

  return "";

}

편집 : 첫째, http://freegeoip.net/ 이제 https://ipstack.com/ (지금은 유료 서비스 일 수도 있음)


http://ipinfo.io를 사용해 보았는데이 JSON API가 완벽하게 작동합니다. 먼저 아래에 언급 된 네임 스페이스를 추가해야합니다.

using System.Linq;
using System.Web; 
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Xml;
using System.Collections.Specialized;

localhost의 경우 더미 데이터를 AU. IP를 하드 코딩하여 결과를 얻을 수 있습니다.

namespace WebApplication4
{
    public partial class WebForm1 : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
         {

          string VisitorsIPAddr = string.Empty;
          //Users IP Address.                
          if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
          {
              //To get the IP address of the machine and not the proxy
              VisitorsIPAddr =   HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
          }
          else if (HttpContext.Current.Request.UserHostAddress.Length != 0)
          {
              VisitorsIPAddr = HttpContext.Current.Request.UserHostAddress;`enter code here`
          }

          string res = "http://ipinfo.io/" + VisitorsIPAddr + "/city";
          string ipResponse = IPRequestHelper(res);

        }

        public string IPRequestHelper(string url)
        {

            string checkURL = url;
            HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
            StreamReader responseStream = new StreamReader(objResponse.GetResponseStream());
            string responseRead = responseStream.ReadToEnd();
            responseRead = responseRead.Replace("\n", String.Empty);
            responseStream.Close();
            responseStream.Dispose();
            return responseRead;
        }


    }
}

클라이언트 IP 주소와 freegeoip.net API를 사용하여 ASP.NET MVC에서이 작업을 수행 할 수있었습니다 . freegeoip.net은 무료이며 라이센스가 필요하지 않습니다.

아래는 내가 사용한 샘플 코드입니다.

String UserIP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(UserIP))
{
    UserIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
string url = "http://freegeoip.net/json/" + UserIP.ToString();
WebClient client = new WebClient();
string jsonstring = client.DownloadString(url);
dynamic dynObj = JsonConvert.DeserializeObject(jsonstring);
System.Web.HttpContext.Current.Session["UserCountryCode"] = dynObj.country_code;

이 게시물통해 자세한 내용 을 확인할 수 있습니다 .


대부분 비용이 드는 외부 API를 사용해야 할 것입니다.

나는 이것을 찾았지만 무료 인 것 같다 : http://hostip.info/use.html


귀국 국가

static public string GetCountry()
{
    return new WebClient().DownloadString("http://api.hostip.info/country.php");
}

용법:

Console.WriteLine(GetCountry()); // will return short code for your country

반품 정보

static public string GetInfo()
{
    return new WebClient().DownloadString("http://api.hostip.info/get_json.php");
}

용법:

Console.WriteLine(GetInfo()); 
// Example:
// {
//    "country_name":"COUNTRY NAME",
//    "country_code":"COUNTRY CODE",
//    "city":"City",
//    "ip":"XX.XXX.XX.XXX"
// }

다음 웹 사이트의 요청 사용

http://ip-api.com/

다음은 국가 및 국가 코드를 반환하는 C # 코드입니다.

public  string GetCountryByIP(string ipAddress)
    {
        string strReturnVal;
        string ipResponse = IPRequestHelper("http://ip-api.com/xml/" + ipAddress);

        //return ipResponse;
        XmlDocument ipInfoXML = new XmlDocument();
        ipInfoXML.LoadXml(ipResponse);
        XmlNodeList responseXML = ipInfoXML.GetElementsByTagName("query");

        NameValueCollection dataXML = new NameValueCollection();

        dataXML.Add(responseXML.Item(0).ChildNodes[2].InnerText, responseXML.Item(0).ChildNodes[2].Value);

        strReturnVal = responseXML.Item(0).ChildNodes[1].InnerText.ToString(); // Contry
        strReturnVal += "(" + 

responseXML.Item(0).ChildNodes[2].InnerText.ToString() + ")";  // Contry Code 
 return strReturnVal;
}

다음은 URL 요청 도우미입니다.

public string IPRequestHelper(string url) {

      HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
      HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();

      StreamReader responseStream = new StreamReader(objResponse.GetResponseStream());
      string responseRead = responseStream.ReadToEnd();

      responseStream.Close();
      responseStream.Dispose();

  return responseRead;
}

필요한 것은 "geo-IP 데이터베이스"입니다. 그들 중 대부분은 (너무 비싸지는 않지만) 약간의 돈, 특히 상당히 정확한 비용이 듭니다. 가장 널리 사용되는 것 중 하나는 MaxMind의 데이터베이스 입니다. 그들은 GeoLity City 라는 IP-to-city 데이터베이스의 상당히 좋은 무료 버전을 가지고 있습니다. 그것은 많은 제한을 가지고 있습니다. 더 정확한 제품.

그리고 예, 사용할 수있는 geo-IP 데이터베이스를 쿼리하는 C # API가 있습니다.


당신에게 좋은 샘플입니다.

public class IpProperties
    {
        public string Status { get; set; }
        public string Country { get; set; }
        public string CountryCode { get; set; }
        public string Region { get; set; }
        public string RegionName { get; set; }
        public string City { get; set; }
        public string Zip { get; set; }
        public string Lat { get; set; }
        public string Lon { get; set; }
        public string TimeZone { get; set; }
        public string ISP { get; set; }
        public string ORG { get; set; }
        public string AS { get; set; }
        public string Query { get; set; }
    }
 public string IPRequestHelper(string url)
    {
        HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
        HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();

        StreamReader responseStream = new StreamReader(objResponse.GetResponseStream());
        string responseRead = responseStream.ReadToEnd();

        responseStream.Close();
        responseStream.Dispose();

        return responseRead;
    }

    public IpProperties GetCountryByIP(string ipAddress)
    {
        string ipResponse = IPRequestHelper("http://ip-api.com/xml/" + ipAddress);
        using (TextReader sr = new StringReader(ipResponse))
        {
            using (System.Data.DataSet dataBase = new System.Data.DataSet())
            {
                IpProperties ipProperties = new IpProperties();
                dataBase.ReadXml(sr);
                ipProperties.Status = dataBase.Tables[0].Rows[0][0].ToString();
                ipProperties.Country = dataBase.Tables[0].Rows[0][1].ToString();
                ipProperties.CountryCode = dataBase.Tables[0].Rows[0][2].ToString();
                ipProperties.Region = dataBase.Tables[0].Rows[0][3].ToString();
                ipProperties.RegionName = dataBase.Tables[0].Rows[0][4].ToString();
                ipProperties.City = dataBase.Tables[0].Rows[0][5].ToString();
                ipProperties.Zip = dataBase.Tables[0].Rows[0][6].ToString();
                ipProperties.Lat = dataBase.Tables[0].Rows[0][7].ToString();
                ipProperties.Lon = dataBase.Tables[0].Rows[0][8].ToString();
                ipProperties.TimeZone = dataBase.Tables[0].Rows[0][9].ToString();
                ipProperties.ISP = dataBase.Tables[0].Rows[0][10].ToString();
                ipProperties.ORG = dataBase.Tables[0].Rows[0][11].ToString();
                ipProperties.AS = dataBase.Tables[0].Rows[0][12].ToString();
                ipProperties.Query = dataBase.Tables[0].Rows[0][13].ToString();

                return ipProperties;
            }
        }
    }

그리고 테스트 :

var ipResponse = GetCountryByIP("your ip address or domain name :)");

API 사용에 대한 대안은 HTML 5 위치 탐색기를 사용하여 브라우저에 사용자 위치를 쿼리하는 것입니다. 주제 질문에서와 유사한 접근 방식을 찾고 있었지만 HTML 5 Navigator가 내 상황에 대해 더 좋고 저렴하다는 것을 알았습니다. 귀하의 시나리오가 다를 수 있음을 고려하십시오. Html5를 사용하여 사용자 위치를 얻는 것은 매우 쉽습니다.

function getLocation()
{
    if (navigator.geolocation)
    {
        navigator.geolocation.getCurrentPosition(showPosition);
    }
    else
    {
        console.log("Geolocation is not supported by this browser.");
     }
}

function showPosition(position)
{
      console.log("Latitude: " + position.coords.latitude + 
  "<br>Longitude: " + position.coords.longitude); 
}

W3Schools Geolocation Tutorial 에서 직접 시도해보십시오.


    public static string GetLocationIPAPI(string ipaddress)
    {
        try
        {
            IPDataIPAPI ipInfo = new IPDataIPAPI();
            string strResponse = new WebClient().DownloadString("http://ip-api.com/json/" + ipaddress);
            if (strResponse == null || strResponse == "") return "";
            ipInfo = JsonConvert.DeserializeObject<IPDataIPAPI>(strResponse);
            if (ipInfo == null || ipInfo.status.ToLower().Trim() == "fail") return "";
            else return ipInfo.city + "; " + ipInfo.regionName + "; " + ipInfo.country + "; " + ipInfo.countryCode;
        }
        catch (Exception)
        {
            return "";
        }
    }

public class IPDataIPINFO
{
    public string ip { get; set; }
    public string city { get; set; }
    public string region { get; set; }
    public string country { get; set; }
    public string loc { get; set; }
    public string postal { get; set; }
    public int org { get; set; }

}

==========================

    public static string GetLocationIPINFO(string ipaddress)
    {            
        try
        {
            IPDataIPINFO ipInfo = new IPDataIPINFO();
            string strResponse = new WebClient().DownloadString("http://ipinfo.io/" + ipaddress);
            if (strResponse == null || strResponse == "") return "";
            ipInfo = JsonConvert.DeserializeObject<IPDataIPINFO>(strResponse);
            if (ipInfo == null || ipInfo.ip == null || ipInfo.ip == "") return "";
            else return ipInfo.city + "; " + ipInfo.region + "; " + ipInfo.country + "; " + ipInfo.postal;
        }
        catch (Exception)
        {
            return "";
        }
    }

public class IPDataIPAPI
{
    public string status { get; set; }
    public string country { get; set; }
    public string countryCode { get; set; }
    public string region { get; set; }
    public string regionName { get; set; }
    public string city { get; set; }
    public string zip { get; set; }
    public string lat { get; set; }
    public string lon { get; set; }
    public string timezone { get; set; }
    public string isp { get; set; }
    public string org { get; set; }
    public string @as { get; set; }
    public string query { get; set; }
}

=============================

    private static string GetLocationIPSTACK(string ipaddress)
    {
        try
        {
            IPDataIPSTACK ipInfo = new IPDataIPSTACK();
            string strResponse = new WebClient().DownloadString("http://api.ipstack.com/" + ipaddress + "?access_key=XX384X1XX028XX1X66XXX4X04XXXX98X");
            if (strResponse == null || strResponse == "") return "";
            ipInfo = JsonConvert.DeserializeObject<IPDataIPSTACK>(strResponse);
            if (ipInfo == null || ipInfo.ip == null || ipInfo.ip == "") return "";
            else return ipInfo.city + "; " + ipInfo.region_name + "; " + ipInfo.country_name + "; " + ipInfo.zip;
        }
        catch (Exception)
        {
            return "";
        }
    }

public class IPDataIPSTACK
{
    public string ip { get; set; }
    public int city { get; set; }
    public string region_code { get; set; }
    public string region_name { get; set; }
    public string country_code { get; set; }
    public string country_name { get; set; }
    public string zip { get; set; }


}

당신은 할 수 있습니다

using System.Net;
using System.IO;
using Newtonsoft.Json.Linq;
public ActionResult geoPlugin()
    {

        var url = "http://freegeoip.net/json/";
        var request = System.Net.WebRequest.Create(url);

        using (WebResponse wrs = request.GetResponse())
        using (Stream stream = wrs.GetResponseStream())
        using (StreamReader reader = new StreamReader(stream))
        {
            string json = reader.ReadToEnd();
            var obj = JObject.Parse(json);
            var City = (string)obj["city"];
            // - For Country = (string)obj["region_name"];                    
            //- For  CountryCode = (string)obj["country_code"];
            Session["CurrentRegionName"]= (string)obj["country_name"];
            Session["CurrentRegion"] = (string)obj["country_code"];
        }
        return RedirectToAction("Index");
    }

참고 URL : https://stackoverflow.com/questions/4327629/get-user-location-by-ip-address

반응형