Commit d7b8d132 authored by szh's avatar szh

添加根据name 获取地址ip

parent 3a5f9e75
......@@ -95,7 +95,7 @@ func broadcast() {
}
//ip 会变化
ip,err := util.GetLocalIP()
ip,err := util.GetLocalIpByName("wlan0")
if err != nil {
tlog.Error("broadcast",err)
}
......@@ -121,7 +121,7 @@ func broadcast() {
if err != nil{
panic(err)
}
tlog.Info("broadcast","udp",send)
tlog.Info("ip:",ip.IP.String(),"broadcast","udp",send)
time.Sleep(time.Second*1)
}
}
\ No newline at end of file
......@@ -44,6 +44,35 @@ func GetLocalIP() (ipv4 *net.IPNet, err error) {
return
}
func GetLocalIpByName(name string) (ipv4 *net.IPNet, err error) {
if name == "" {
return nil,errors.New("name not empty")
}
inter,err := net.InterfaceByName(name)
if err != nil {
return nil,err
}
var (
addrs []net.Addr
ipNet *net.IPNet // IP地址
isIpNet bool
)
if addrs,err = inter.Addrs(); err != nil {
return nil,err
}
for _, addr := range addrs {
if ipNet, isIpNet = addr.(*net.IPNet); isIpNet && !ipNet.IP.IsLoopback(){
// 跳过IPV6
if ipNet.IP.To4() != nil{
ipv4 = ipNet// 192.168.1.1
return
}
}
}
return nil,nil
}
func GetExternal() (string,error) {
resp, err := http.Get("http://myexternalip.com/raw")
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment