Golang 获取当前外网IP/地址/运营商

通过 Golang 获取当前外网IP、地址、运营商 此功能仅用于查看本机公网地址,请勿用于其他用途,并遵守中国法律法规。

1. 获取本机外网 IP

1.1 代码

package main

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

func main() {

	responseClient, errClient := http.Get("https://ipw.cn/api/ip/myip")

	if errClient != nil {
		fmt.Printf("获取外网 IP 失败,请检查网络\n")
		panic(errClient)
	}
	defer responseClient.Body.Close()

	// 获取 http response 的 body
	body, _ := ioutil.ReadAll(responseClient.Body)
	clientIP := string(body)

	print(clientIP)

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

1.2 返回

go run getip.go

106.224.145.147
1
2
3

2. 获取本机外网 IP 及地理位置

2.1 代码

package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {

	type Address struct {
		Country  string `json:"Country"`
		Province string `json:"Province"`
		City     string `json:"City"`
	}

	type IPLocate struct {
		Result  bool    `json:"result"`
		IP      string  `json:"IP"`
		Address Address `json:"Address"`
		ISP     string  `json:"ISP"`
	}


	responseClient, errClient := http.Get("https://ipw.cn/api/ip/locate") // 获取外网 IP
	if errClient != nil {
		fmt.Printf("获取外网 IP 失败,请检查网络\n")
		panic(errClient)
	}
	// 程序在使用完 response 后必须关闭 response 的主体。
	defer responseClient.Body.Close()

	body, _ := ioutil.ReadAll(responseClient.Body)

	var ipLocateResult IPLocate
	err := json.Unmarshal(body, &ipLocateResult)
	if err != nil {
		fmt.Println(err)
	}

	result := ipLocateResult.Result
	ip := ipLocateResult.IP
	country := ipLocateResult.Address.Country
	province := ipLocateResult.Address.Province
	city := ipLocateResult.Address.City
	isp := ipLocateResult.ISP

	fmt.Printf("Result: %t\n", result)
	fmt.Printf("IP: %s\n", ip)
	fmt.Printf("Addresss: %s,%s,%s\n", country, province, city)
	fmt.Printf("ISP: %s\n", isp)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53

2.2 返回

go run getiplocate.go

Result: true
IP: 106.224.145.147
Addresss: 中国,江西,南昌
ISP: 电信
1
2
3
4
5
6

reference