【问题标题】:How do I get my public ip address in a shell script?如何在 shell 脚本中获取我的公共 IP 地址?
【发布时间】:2012-05-25 17:50:39
【问题描述】:

此命令返回我的 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

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

【问题讨论】:

  • 以下对我有用 "dig @resolver1.opendns.com myip.opendns.com | grep ^myip.opendns.com | tr '\t' : | cut -d: -f5"

标签: linux shell networking dns dig


【解决方案1】:

不要让它变得比它需要的更难......使用+short

[mpenning@Bucksnort ~]$ dig +short mike.homeunix.com
76.21.48.169
[mpenning@Bucksnort ~]$

【讨论】:

    【解决方案2】:

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

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

    注意:我的假设是您计划提取在“ANSWER SECTION”之后打印的 ip

    【讨论】:

      【解决方案3】:
      dig +short myip.opendns.com @resolver1.opendns.com
      

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

      【讨论】:

      • 为什么要使用起酥油?此外,这应该是一个 shell 脚本,而不是 URL。
      • 因为结果应该只有 IP 地址,没有其他信息,这就是我使用它的原因。此外,这是一个 shell 命令,应该是一个命令,而不是脚本。 URL 仅作为使用示例。
      【解决方案4】:

      另一种方法是:

      sudo apt install stuntman-client
      

      然后

      myip=$(stunclient --localport 8888 stun.l.google.com 19302|grep Mapped|cut -d ":" -f 2|tr -d " ")
      

      【讨论】:

        猜你喜欢
        • 2017-09-23
        • 1970-01-01
        • 2016-05-27
        • 1970-01-01
        • 2017-10-31
        • 2011-03-16
        • 2013-10-17
        • 1970-01-01
        • 2011-01-22
        相关资源
        最近更新 更多