Skip to content

Instantly share code, notes, and snippets.

@zonque
Created March 20, 2019 08:20
Show Gist options
  • Save zonque/2aa29ecb875059115b57aee30adeb9a8 to your computer and use it in GitHub Desktop.
Save zonque/2aa29ecb875059115b57aee30adeb9a8 to your computer and use it in GitHub Desktop.
Get local IP that a given host can reach the local machine on
package main
import (
"fmt"
"log"
"net"
)
func localAddrForHost(host string) (string, error) {
conn, err := net.Dial("udp", host + ":12345")
if err != nil {
return "", err
}
localAddr := conn.LocalAddr().(*net.UDPAddr)
return localAddr.IP.String(), nil
}
func main() {
h := "192.168.122.100"
l, err := localAddrForHost(h)
if err != nil {
log.Fatalf("%v", err)
}
fmt.Printf("Local address for %s: %s\n", h, l)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment