MyTetra Share
Делитесь знаниями!
О, смотри-ка какое хорошее место. Дайте два!
Get my country by IP in bash
Раздел: root - Linux - Console - bash

Use another IP locator than that provides with that information like:

curl -s ''


curl -s ''

(see the API for details)


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


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

for more precision, or:

curl -s |
  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 | grep -iE ^country: | awk '{print $2}' gives me what I 

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

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