kraken icon indicating copy to clipboard operation
kraken copied to clipboard

Feature/outbond ip

Open jadeydi opened this issue 2 years ago • 5 comments

jadeydi avatar Feb 22 '22 05:02 jadeydi

This exactly changes the original behavior. I think this change can be applied when neither address nor interface is configured.

So if address use address, then if interface query from interface, otherwise from DNS

cedricfung avatar Feb 22 '22 06:02 cedricfung

Fixed

jadeydi avatar Feb 22 '22 09:02 jadeydi

Have you tested if this work on some cloud servers? Because I can see we have some pion code using the engine Interface and IP.

cedricfung avatar Feb 22 '22 09:02 cedricfung

func GetOutboundIP() {
	log.Println(GetOutboundIP2())
	log.Println(getIPFromInterface())
}

// Get preferred outbound ip of this machine
func GetOutboundIP2() string {
	conn, err := net.Dial("udp", "8.8.8.8:80")
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	localAddr := conn.LocalAddr().(*net.UDPAddr)

	return localAddr.IP.String()
}

func getIPFromInterface() (string, error) {
	iname := "eth0"

	ifaces, err := net.Interfaces()
	if err != nil {
		return "", err
	}
	for _, i := range ifaces {
		if i.Name != iname {
			continue
		}
		addrs, err := i.Addrs()
		if err != nil {
			return "", err
		}
		for _, addr := range addrs {
			switch v := addr.(type) {
			case *net.IPNet:
				return v.IP.String(), nil
			case *net.IPAddr:
				return v.IP.String(), nil
			}
		}
	}

	return "", fmt.Errorf("no address for interface %s", iname)
}

Tests in Google cloud:

2022/02/22 09:17:09 10.128.x.x 2022/02/22 09:17:09 no address for interface eth0

Tests in Aliyun: 2022/02/22 17:17:27 172.2x.1xx.90 2022/02/22 17:17:27 172.2x.1xx.90

Discussions in stakeoverflow: https://stackoverflow.com/questions/23558425/how-do-i-get-the-local-ip-address-in-go

jadeydi avatar Feb 22 '22 09:02 jadeydi

I mean your new modifications, leave interface and address empty.

And for the specific error, that's just because you were not using a correct interface name. Use ip addr to see available interfaces at first.

cedricfung avatar Feb 22 '22 09:02 cedricfung