6

This command returns my ip address with additional information.

dig @resolver1.opendns.com myip.opendns.com
; <<>> DiG 9.6-ESV-R4-P3 <<>> @resolver1.opendns.com myip.opendns.com
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 48206
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION: 
;myip.opendns.com.      IN  A

;; ANSWER SECTION:
myip.opendns.com.   0   IN  A   122.167.119.178

;; Query time: 199 msec
;; SERVER: 208.67.222.222#53(208.67.222.222)
;; WHEN: Fri May 18 11:46:51 2012
;; MSG SIZE  rcvd: 50

I only want to extract my ip address from this. How can I extract my ip address from the dig output?

Mike Pennington
  • 41,899
  • 19
  • 136
  • 174
Deepan Chakravarthy
  • 4,154
  • 7
  • 25
  • 21

4 Answers4

15

Don't make this harder than it needs to be... use +short

[mpenning@Bucksnort ~]$ dig +short mike.homeunix.com
76.21.48.169
[mpenning@Bucksnort ~]$
Mike Pennington
  • 41,899
  • 19
  • 136
  • 174
3

If you are using bash shell this will work for you

grep -A1 "ANSWER SECTION" ip_file.txt  | awk '{if(NF==5)print $5;}'

NOTE: My assumption is you are planning to extract the ip printed after the "ANSWER SECTION"

Raghuram
  • 3,937
  • 2
  • 19
  • 25
1
dig +short myip.opendns.com @resolver1.opendns.com

From my blog: http://blog.valch.name/2016/03/17/show-your-ip/

Tunaki
  • 132,869
  • 46
  • 340
  • 423
valch85
  • 99
  • 1
  • 8
  • Why do you wanna use a shortener? Moreover, this is supposed to be a shell script, not a URL. – Praveen Kumar Purushothaman Mar 17 '16 at 09:53
  • because the result should be with only IP address, without additional info, that why I use it. Moreover, this is a shell command and supposed to be a command, not a script. URL just for an example of usage. – valch85 Mar 19 '16 at 01:25
1

An alternative way is:

sudo apt install stuntman-client

then

myip=$(stunclient --localport 8888 stun.l.google.com 19302|grep Mapped|cut -d ":" -f 2|tr -d " ")
Zibri
  • 9,096
  • 3
  • 52
  • 44
  • 1
    For Ubuntu 20.04, `sudo apt install stun; myip=$(stun stun.l.google.com -v 2>&1 | grep MappedAddress | cut -d: -f1 | awk '{print $NF}' | head -1)` – Calvin Kim Aug 29 '22 at 21:02