MyTetra Share
Делитесь знаниями!
https://ru.gaming-goods.com/
Get my country by IP in bash
Время создания: 09.04.2014 13:45
Раздел: root - Linux - Console - bash
Запись: Yurons/mytetra/master/base/1397040357vhj6mo0gky/text.html на raw.github.com

Use another IP locator than ifconfig.me that provides with that information like:

curl -s 'http://geoiplookup.net/geoapi.php?output=countrycode'

or:

curl -s 'http://geoiplookup.net/geoapi.php?output=country'

(see the API  for details)

or:

curl -s http://whatismycountry.com/ |
  sed -n 's|.*,\(.*\)</h1>|\1|p'

or:

curl -s http://whatismycountry.com/ |
  sed -n 's|.*> *\(.*\)</h1>|\1|p'

for more precision, or:

curl -s http://whatismycountry.com/ |
  sed -n 's/.*Coordinates \(.*\)<.*/\1/p'

for the coordinates.

That makes assumptions on the HTML formatting of the page. So it may stop working if they decide to change that format in the future.

You can get somewhat close by querying the public whois database. It'll likely be somewhat difficult to "productify" to handle every possible case, but a reasonable approximation might be:

$ whois a.b.c.d | grep -iE ^country:

where a.b.c.d is the IP address in question.

whois is often installed by default, so this meets a reasonable interpretation of your "I prefer not to install any package for doing this" read as "I don't want to install additional software".

To print only the value of the country field and force it to upper case only (to make comparisons easier, for example), you can do something like:

$ whois a.b.c.d | awk -F':[ \t]+' 'tolower($1) ~ /^country$/ { print toupper($2) 

whois $(curl ifconfig.me) | grep -iE ^country: | awk '{print $2}' gives me what I 

@Radu You can save yourself one pipe by doing whois $(curl ifconfig.me) | awk 'tolower($1) ~ /^country:/ { print $2 }' instead. 

 
MyTetra Share v.0.65
Яндекс индекс цитирования