Created
March 20, 2019 08:20
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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