获取网卡IPv4地址
package main
import (
"fmt"
"net"
)
func main() {
ifname := "ens33"
netIf, err := net.InterfaceByName(ifname)
if err != nil {
fmt.Printf("get netIf by name %s failed, err is %v\n", ifname, err)
return
}
addrs, err := netIf.Addrs()
if err != nil {
fmt.Printf("get addrs by name %s failed, err is %v\n", ifname, err)
return
}
for _, addr := range addrs {
ipNet, ok := addr.(*net.IPNet)
if ok && ipNet.IP.To4() != nil {
fmt.Printf("ipv4 addr is %s\n", ipNet.IP.String())
return
}
}
}
IP整型和字符串互转
package main
import (
"fmt"
"net"
)
func IPv4StringToUint32(ip string) (uint32, error) {
p := net.ParseIP(ip).To4()
if p == nil {
return 0, fmt.Errorf("invalid ipv4 format")
}
return uint32(p[3])<<24 | uint32(p[2])<<16 | uint32(p[1])<<8 | uint32(p[0]), nil
}
func IPv4Uint32ToString(ipUint32 uint32) (string, error) {
ip := make(net.IP, net.IPv4len)
ip[3] = byte(ipUint32 >> 24)
ip[2] = byte(ipUint32 >> 16)
ip[1] = byte(ipUint32 >> 8)
ip[0] = byte(ipUint32)
return ip.String(), nil
}
func main() {
ip := "100.101.102.103"
ipUint32, err := IPv4StringToUint32(ip)
if err != nil {
fmt.Printf("get ipv4 uint32 from string %s failed, err is %v", ip, err)
return
}
fmt.Println(ipUint32)
ipString, err := IPv4Uint32ToString(ipUint32)
if err != nil {
fmt.Printf("get ipv4 string from uint32 %d failed, err is %v", ipUint32, err)
return
}
fmt.Println(ipString)
}
解析cidr子网
package main
import (
"fmt"
"net"
)
func main() {
cidrs := []string{"100.101.102.1/16", "100.101.102.1"}
for _, cidr := range cidrs {
_, ipNet, err := net.ParseCIDR(cidr)
if err != nil {
fmt.Printf("parse cidr %s failed, err is %v\n", cidr, err)
continue
}
mask, _ := ipNet.Mask.Size()
fmt.Printf("parse cidr %s result is %s/%d\n", cidr, ipNet.IP.String(), mask)
}
}
标签:return,nil,err,ip,fmt,网络,用法,go,cidr
From: https://www.cnblogs.com/WJQ2017/p/18088650