adsense_in_article_test


[bash: curl] IP주소/도메인의 국적 및 위치 조회하기 리눅스 bash script

shell script로 작업을 하면서 특정 IP주소 또는 도메인이 속한 국적과 위치가 필요할 경우가 있다면, IP주소에 대응되는 위치를 알려주는 웹사이트인 freegeoip.net에 조회를 요청해 보자.

물론 웹브라우저로 들어가서 검색창에 IP주소나 도메인을 입력해서 조회를 할 수도 있다.

아무튼, 이 서비스를 shell script에서 사용하기 위해서는 curl을 이용하면 된다. 일단 아래의 예시를 보자. 결과를 xml 형식으로 받은 경우이다.

curl freegeoip.net/xml/www.google.com
<?xml version="1.0" encoding="UTF-8"?>
<Response>
 <Ip>173.194.77.104</Ip>
 <CountryCode>US</CountryCode>
 <CountryName>United States</CountryName>
 <RegionCode>CA</RegionCode>
 <RegionName>California</RegionName>
 <City>Mountain View</City>
 <ZipCode>94043</ZipCode>
 <Latitude>37.4192</Latitude>
 <Longitude>-122.0574</Longitude>
 <MetroCode>807</MetroCode>
 <AreaCode>650</AreaCode>
</Response>

IP주소로도 조회 가능하며, 결과는 동일하다.

curl freegeoip.net/xml/173.194.77.104

결과의 내용은 IP주소(Ip), 국가코드(CountryCode), 국명(CountryName), 주 코드(RegionCode), 주명(RegionName), 도시(City), 우편번호(ZipCode), 위도(Latitude), 경도(Longitude), MetroCode(뭔지 모르겠다-_-;), 지역번호(AreaCode)

국내 도메인을 검색해 보면 국가 정도까지는 조회가 되고, 도시 정보는 안 나오는 듯.

curl freegeoip.net/xml/www.egloos.com
<?xml version="1.0" encoding="UTF-8"?>
<Response>
 <Ip>125.141.132.118</Ip>
 <CountryCode>KR</CountryCode>
 <CountryName>Korea, Republic of</CountryName>
 <RegionCode></RegionCode>
 <RegionName></RegionName>
 <City></City>
 <ZipCode></ZipCode>
 <Latitude>37.57</Latitude>
 <Longitude>126.98</Longitude>
 <MetroCode></MetroCode>
 <AreaCode></AreaCode>
</Response>

curl이 동작하는 과정을 상세히 출력하려면 -v 옵션을, 에러 메시지나 동작 과정을 출력하지 않고 싶다면 -s 옵션을 사용하자.

# verbose
curl -v freegeoip.net/xml/www.egloos.com

# silent
curl -s freegeoip.net/xml/www.egloos.com

아래의 예시를 참고하자. 특정 도메인에 대응되는 IP주소와 국가코드를 각각 변수에 할당하는 경우이다.

domain="www.egloos.com"

# curl 실행, 임시파일 result.tmp에 결과 저장
curl -s freegeoip.net/xml/$domain > result.tmp
# IP주소 추출
ip_addr=`cat result.tmp | grep "<Ip>" | cut -d'>' -f2 | cut -d'<' -f1`
# 국가코드 추출
country_code=`cat result.tmp | grep "<CountryCode>" | cut -d'>' -f2 | cut -d'<' -f1`
# 결과 출력
echo "$domain - $ip_addr - $country_code"

cut 명령에 대한 설명은 이전 게시물을 참고하자.

xml 형식뿐만 아니라 csv, json 형식도 지원하므로 편한대로 골라 쓰면 된다.

# csv 형식 출력
curl freegeoip.net/csv/www.google.com
"74.125.227.176","US","United States","CA","California","Mountain View","94043","37.4192","-122.0574","807","650"

# json 형식 출력
curl freegeoip.net/json/www.google.com
{"ip":"173.194.46.17","country_code":"US","country_name":"United States","region_code":"CA","region_name":"California","city":"Mountain View","zipcode":"94043","latitude":37.4192,"longitude":-122.0574,"metro_code":"807","area_code":"650"}



덧글

  • 2016/06/17 16:47 # 삭제 답글 비공개

    비공개 덧글입니다.
  • 반달가면 2016/06/17 21:29 #

    제가 도움이 될지 안될지는 모르겠습니다만, 무엇을 어떻게 적용하려 하시는제 좀 더 구체적으로 얘기해 주셔야 될 것 같습니다. 카톡보다는 메일이 나을 듯합니다. xubuntu_kr 골뱅이 outlook.com 으로 문의해 주시기 바랍니다.
댓글 입력 영역
* 비로그인 덧글의 IP 전체보기를 설정한 이글루입니다.



통계 위젯 (화이트)

19178
2704
2506808

2019 대표이글루_IT

B-Side