代码
//auto_join_host_port.go
package main
import (
"fmt"
"net"
)
func GetLocalIP() string {
addrs, err := net.InterfaceAddrs()
if err != nil {
return ""
}
fmt.Println("net.InterfaceAddrs", addrs)
for _, address := range addrs {
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
return ipnet.IP.String()
}
}
}
return ""
}
func main() {
_, port, _ := net.SplitHostPort("0.0.0.0:7052")
fmt.Println("net.SplitHostPort 0.0.0.0:7052, port", port)
address := net.JoinHostPort(GetLocalIP(), port)
fmt.Println("net.JoinHostPort(GetLocalIP(), port)", address)
}
编译运行
go build auto_join_host_port.go
./auto_join_host_port
net.SplitHostPort 0.0.0.0:7052, port 7052
net.InterfaceAddrs [127.0.0.1/8 192.168.29.132/24 192.168.122.1/24 172.17.0.1/16 172.18.0.1/16 172.19.0.1/16 ::1/128 fe80::d0c4:baf2:b056:6b4a/64 fe80::42:6bff:fe53:fbbd/64 fe80::42:2ff:fe3e:6cc8/64 fe80::2c86:27ff:fee8:b2da/64 fe80::103c:a8ff:fe9f:59f7/64 fe80::48d4:6fff:fef1:c794/64 fe80::98db:66ff:fe71:67a/64 fe80::7474:d9ff:fe6a:8296/64 fe80::f06c:a0ff:feae:785b/64 fe80::bcc6:fff:fe4f:1418/64 fe80::9462:f2ff:fe30:571/64]
net.JoinHostPort(GetLocalIP(), port) 192.168.29.132:7052
参考文档
https://github.com/hyperledger/fabric/blob/release/core/peer/peer.go