Skip to content

Conversation

@jadeydi
Copy link
Member

@jadeydi jadeydi commented Feb 22, 2022

No description provided.

@cedricfung
Copy link
Contributor

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

@jadeydi
Copy link
Member Author

jadeydi commented Feb 22, 2022

Fixed

@cedricfung
Copy link
Contributor

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.

@jadeydi
Copy link
Member Author

jadeydi commented Feb 22, 2022

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

@cedricfung
Copy link
Contributor

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants