本文章是学习Go中net包的一篇笔记,记录 net 包的一些方法的使用。
1、func SplitHostPort(hostport string) (host, port string, err error)
函数将格式为”host:port”、”[host]:port”或”[ipv6-host%zone]:port”的网络地址分割为host或ipv6-host%zone和port两个部分。
2、func JoinHostPort(host, port string) string
函数将host和port合并为一个网络地址。一般格式为”host:port”;如果host含有冒号或百分号,格式为”[host]:port”。
3、type HardwareAddr []byte
HardwareAddr类型代表一个硬件地址(MAC地址)
3.1、func ParseMAC(s string) (hw HardwareAddr, err error)
ParseMAC函数使用如下格式解析一个IEEE 802 MAC-48、EUI-48或EUI-64硬件地址:
01:23:45:67:89:ab 01:23:45:67:89:ab:cd:ef 01-23-45-67-89-ab 01-23-45-67-89-ab-cd-ef 0123.4567.89ab 0123.4567.89ab.cdef
3.2、func (a HardwareAddr) String() string
4、网卡的状态标识
type Flags uint const ( FlagUp Flags = 1 << iota // 接口在活动状态 1 FlagBroadcast // 接口支持广播 2 FlagLoopback // 接口是环回的 4 FlagPointToPoint // 接口是点对点的 8 可以理解为单播 FlagMulticast // 接口支持组播 16 和多播同义 )
var flagNames = []string{
"up",
"broadcast",
"loopback",
"pointtopoint",
"multicast",
}
4.1 func (f Flags) String() string
5、网卡的相关的方法
type Interface struct {
Index int // 索引,>=1的整数
MTU int // 最大传输单元
Name string // 接口名,例如"en0"、"lo0"、"eth0.100"
HardwareAddr HardwareAddr // 硬件地址,IEEE MAC-48、EUI-48或EUI-64格式
Flags Flags // 接口的属性,例如FlagUp、FlagLoopback、FlagMulticast
}
5.1、func Interfaces() ([]Interface, error)
Interfaces返回该系统的网络接口列表。
例如:(输出结果为了现实方便,使用json输出)
[
{
"Index": 1,
"MTU": 16384,
"Name": "lo0",
"HardwareAddr": null,
"Flags": 21 //相当于 up|loopback|multicast ,网卡使用中,支持环回、组播
},
{
"Index": 9,
"MTU": 1484,
"Name": "awdl0",
"HardwareAddr": "yvQEMXJ1",
"Flags": 18 //相当于broadcast|multicast,网卡未使用,支持广播、组播
},
{
"Index": 5,
"MTU": 1500,
"Name": "en4",
"HardwareAddr": "aFs1niJI",
"Flags": 19 //相当于 up|broadcast|multicast,网卡使用中,支持广播、组播
}
]
5.2 、func InterfaceByIndex(index int) (*Interface, error)
InterfaceByIndex返回指定索引的网络接口。
例如:
interfaces,_ := net.InterfaceByIndex(5)
json , _ := json.Marshal(interfaces)
输出:
{
"Index": 5,
"MTU": 1500,
"Name": "en4",
"HardwareAddr": "aFs1niJI",
"Flags": 19
}
5.3、func InterfaceByName(name string) (*Interface, error)
InterfaceByName返回指定名字的网络接口
interfaces,_ := net.InterfaceByName("awdl0")
json , _ := json.Marshal(interfaces)
输出:
{
"Index": 9,
"MTU": 1484,
"Name": "awdl0",
"HardwareAddr": "yvQEMXJ1",
"Flags": 18
}
5.4、func (ifi *Interface) Addrs() ([]Addr, error)
Addrs方法返回网络接口ifi的一或多个接口地址。
inter,_ := net.InterfaceByIndex(5) addrs, _ := inter.Addrs() fmt.Println(addrs) 输出: [fe80::6a5b:35ff:fe9e:2248/64 10.1.81.38/23]
5.5、func (ifi *Interface) MulticastAddrs() ([]Addr, error)
MulticastAddrs返回网络接口ifi加入的多播组地址。
inter,_ := net.InterfaceByIndex(5)
addrs, _ := inter.MulticastAddrs()
json , _ := json.Marshal(addrs)
fmt.Fprintf(c.Writer, string(json))
输出:
[
{
"IP": "224.0.0.251",
"Zone": ""
}, {
"IP": "ff02::fb",
"Zone": ""
},{
"IP": "224.0.0.1",
"Zone": ""
},{
"IP": "ff01::1",
"Zone": ""
}, {
"IP": "ff02::2:ff4d:9ef2",
"Zone": ""
}, {
"IP": "ff02::1",
"Zone": ""
}, {
"IP": "ff02::1:ff9e:2248",
"Zone": ""
}]
6、网络终端
type Addr interface {
Network() string // 网络名
String() string // 字符串格式的地址
}
