4 changed files with 87 additions and 4 deletions
@ -0,0 +1,49 @@ |
|||
package config |
|||
|
|||
import ( |
|||
"fmt" |
|||
"net" |
|||
) |
|||
|
|||
type Config struct { |
|||
DeviceName string |
|||
Port string |
|||
LocalIP string |
|||
FilePath string |
|||
Version string |
|||
} |
|||
|
|||
var G Config |
|||
|
|||
// 本地ip
|
|||
func getLocalIP() (string, error) { |
|||
addrs, err := net.InterfaceAddrs() |
|||
if err != nil { |
|||
return "", err |
|||
} |
|||
var ips []string |
|||
for _, address := range addrs { |
|||
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { |
|||
if ipnet.IP.To4() != nil { |
|||
ips = append(ips, ipnet.IP.String()) |
|||
} |
|||
} |
|||
} |
|||
if len(ips) == 0 { |
|||
return "", fmt.Errorf("get local ip failed") |
|||
} else if len(ips) == 1 { |
|||
return ips[0], nil |
|||
} else { |
|||
// Select the one connected to the network
|
|||
// when there are multiple network interfaces
|
|||
|
|||
// Is there a better way?
|
|||
c, err := net.Dial("udp", "8.8.8.8:80") |
|||
if err != nil { |
|||
return ips[0], nil |
|||
} |
|||
defer c.Close() |
|||
return c.LocalAddr().(*net.UDPAddr).IP.String(), nil |
|||
} |
|||
|
|||
} |
|||
Loading…
Reference in new issue