ipKit

package
v2.2.11 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 7, 2023 License: Apache-2.0 Imports: 6 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AssertIPv4

func AssertIPv4(ipv4 string) error

AssertIPv4

e.g.

("192.168.9.254")	=> nil
("127.0.0.1")	 	=> nil
("localhost")	 	=> test/test1.go:11|main [Assertion failed] ipv4(localhost) is invalid(Key: '' Error:Field validation for '' failed on the 'ipv4' tag)
("::1")	 			=> test/test1.go:12|main [Assertion failed] ipv4(::1) is invalid(Key: '' Error:Field validation for '' failed on the 'ipv4' tag)

func GetLocalIPs

func GetLocalIPs() ([]string, error)

GetLocalIPs

流程:

使用 net.InterfaceAddrs() 来获取所有网卡的地址,然后遍历这些地址,找到 IPv4地址 且 不是回环地址 的IP地址

缺陷:

这种方法无法直接获取到对外的IP地址,只能判断IPv4和非回环地址,多IP情况还需要额外进行判断。

func GetOutboundIP

func GetOutboundIP() (string, error)

GetOutboundIP 获取: 对外的ip地址

系统性能数据gopsutil库

https://topgoer.com/%E5%85%B6%E4%BB%96/%E7%B3%BB%E7%BB%9F%E6%80%A7%E8%83%BD%E6%95%B0%E6%8D%AEgopsutil%E5%BA%93.html

通过 UDP 获取本机 IP

http://t.zoukankan.com/fousor-p-14874576.html

PS: 由于会申请一个UDP的端口,所以如果经常调用也会比较耗时的,这里如果需要可以将查询到的IP给缓存起来,性能可以获得很大提升.

流程: (1) 使用 net.Dial 连接到一个外部地址(例如“8.8.8.8:53”), (2) 然后通过 conn.LocalAddr() 获取到本地IP地址.

优点:

这种方法可以直接获取到对外的IP地址.
(a) 使用 UDP 的优点是不需要关注是否送达,只需要对应的 {ip}:{port} 结构正确,即可获取到IP地址;
(b) 这里使用TCP 也是可以的,只是需要保证对应的 {ip}:{port} 连通性.

func IsIP

func IsIP(str string) bool

IsIP 检查传参是否为ip(支持ipv4和ipv6)?

参考:https://www.php.cn/be/go/441401.html

func IsIPv4

func IsIPv4(str string) bool

IsIPv4

"0.0.0.0" => true "127.0.0.1" => true

func IsIPv6

func IsIPv6(str string) bool

Types

type IpInfo

type IpInfo struct {
	Type int
	IP   net.IP
}

func GetIpInfo

func GetIpInfo(str string) IpInfo

GetIpInfo 获取ip字符串的信息.

@param str 字符串,IPv4 或 IPv6

func (IpInfo) IsIP

func (info IpInfo) IsIP() bool

func (IpInfo) IsIPv4

func (info IpInfo) IsIPv4() bool

func (IpInfo) IsIPv6

func (info IpInfo) IsIPv6() bool

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL