如何在shell脚本中获取公共IP地址?

时间:2022-07-18 07:09:32

This command returns my ip address with additional information.

此命令返回我的IP地址以及其他信息。

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?

我只想从中提取我的IP地址。如何从dig输出中提取我的ip地址?

3 个解决方案

#1


14  

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 ~]$

#2


3  

If you are using bash shell this will work for you

如果您使用的是bash shell,这对您有用

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"

注意:我的假设是你计划在“答案部分”之后提取ip打印

#3


1  

dig +short myip.opendns.com @resolver1.opendns.com

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

来自我的博客:http://blog.valch.name/2016/03/17/show-your-ip/

#1


14  

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 ~]$

#2


3  

If you are using bash shell this will work for you

如果您使用的是bash shell,这对您有用

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"

注意:我的假设是你计划在“答案部分”之后提取ip打印

#3


1  

dig +short myip.opendns.com @resolver1.opendns.com

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

来自我的博客:http://blog.valch.name/2016/03/17/show-your-ip/