mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-04 12:52:28 +08:00
85 lines
1.8 KiB
Go
85 lines
1.8 KiB
Go
package netutil
|
|
|
|
import (
|
|
"encoding/json"
|
|
"io/ioutil"
|
|
"net"
|
|
"net/http"
|
|
)
|
|
|
|
// GetInternalIp return internal ipv4
|
|
func GetInternalIp() string {
|
|
addr, err := net.InterfaceAddrs()
|
|
if err != nil {
|
|
panic(err.Error())
|
|
}
|
|
for _, a := range addr {
|
|
if ipNet, ok := a.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
|
|
if ipNet.IP.To4() != nil {
|
|
return ipNet.IP.String()
|
|
}
|
|
}
|
|
}
|
|
|
|
return ""
|
|
}
|
|
|
|
// GetPublicIpInfo return public ip information
|
|
// return the PublicIpInfo struct
|
|
func GetPublicIpInfo() (*PublicIpInfo, error) {
|
|
resp, err := http.Get("http://ip-api.com/json/")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
body, err := ioutil.ReadAll(resp.Body)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
var ip PublicIpInfo
|
|
err = json.Unmarshal(body, &ip)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &ip, nil
|
|
}
|
|
|
|
// PublicIpInfo public ip info: country, region, isp, city, lat, lon, ip
|
|
type PublicIpInfo struct {
|
|
Status string `json:"status"`
|
|
Country string `json:"country"`
|
|
CountryCode string `json:"countryCode"`
|
|
Region string `json:"region"`
|
|
RegionName string `json:"regionName"`
|
|
City string `json:"city"`
|
|
Lat float64 `json:"lat"`
|
|
Lon float64 `json:"lon"`
|
|
Isp string `json:"isp"`
|
|
Org string `json:"org"`
|
|
As string `json:"as"`
|
|
Ip string `json:"query"`
|
|
}
|
|
|
|
// IsPublicIP verify a ip is public or not
|
|
func IsPublicIP(IP net.IP) bool {
|
|
if IP.IsLoopback() || IP.IsLinkLocalMulticast() || IP.IsLinkLocalUnicast() {
|
|
return false
|
|
}
|
|
if ip4 := IP.To4(); ip4 != nil {
|
|
switch {
|
|
case ip4[0] == 10:
|
|
return false
|
|
case ip4[0] == 172 && ip4[1] >= 16 && ip4[1] <= 31:
|
|
return false
|
|
case ip4[0] == 192 && ip4[1] == 168:
|
|
return false
|
|
default:
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|