package main
import (
"fmt"
"net"
"strings"
)
func main() {
ipList, err := GetLocalIPList()
if err != nil {
fmt.Printf("err=%v\n", err)
return
}
for name := range ipList {
fmt.Printf("%v, %v\n", name, ipList[name])
}
}
// 返回map[网卡名]ip地址
func GetLocalIPList() (map[string]string, error) {
interfaceList, err := net.Interfaces()
if err != nil {
return nil, err
}
var byName *net.Interface
var addrList []net.Addr
var oneAddrs []string
ipList := make(map[string]string, len(interfaceList))
for i := range interfaceList {
byName, err = net.InterfaceByName(interfaceList[i].Name)
if err != nil {
return nil, err
}
addrList, err = byName.Addrs()
if err != nil {
return nil, err
}
for ii := range addrList {
oneAddrs = strings.SplitN(addrList[ii].String(), "/", 2)
ipList[interfaceList[i].Name] = oneAddrs[0]
}
}
return ipList, nil
}