Bootstrap

获取自己的公网 IP 地址

在日常维护过程中,我们经常需要获取自己的公网 IP 地址,获取方式有很多种。

  • 询问网络管理员

  • 通过浏览器访问特定网站

  • 通过命令来获取。

今天我们来看看如何通过 IPIP.net 提供的数据库来获取自己的公网 IP 地址,尤其适合中间经过 NAT 的网络环境。

我新建一个 test.sh 的文件,在文件内键入如下内容:

[root@erdong ~]# cat test.sh
#!/bin/bash

ip=$(curl -s http://myip.ipip.net)
echo "My public IP address is: $ip"
[root@erdong ~]#

然后执行这个文件,就可以看到当前的 IP 地址,以及地理位置和运营商。

[root@erdong ~]# sh test.sh
My public IP address is: 当前 IP:47.92.127.3  来自于:中国 北京 北京  阿里云/电信/联通/移动/教育网
[root@erdong ~]#

直接在浏览器访问 http://myip.ipip.net 也会得到你当前的公网 IP 地址和地理位置和运营商。

如果是在海外使用,建议使用域名 https://myip.la 。

当然除了 shell 你也可以使用 Python,

# This example requires the requests library be installed.  You can learn more
# about the Requests library here: http://docs.python-requests.org/en/latest/
from requests import get

ip = get('https://api.myip.la').text
print('My public IP address is: {}'.format(ip))

也可以使用 Go,编译一下,就可以导出运行。

package main

import (
        "io/ioutil"
        "net/http"
        "os"
)

func main() {
        res, _ := http.Get("https://api.myip.la")
        ip, _ := ioutil.ReadAll(res.Body)
        os.Stdout.Write(ip)
}

ok ,结束。