--
package main
import (
"fmt"
"net"
)
func main(){
ip, _ := net.LookupIP("google.net")
fmt.Println(ip)
I wrote a small program to print the host's external IPs: https://github.com/mccoyst/myip/blob/master/myip.goIt's been a while and I don't recall why I didn't use net.InterfaceAddrs(), though it actually seems like less programming effort than manually filtering out the loopbacks. However, I could be convinced that it'd be worth changing.
On Monday, September 24, 2012 5:10:27 AM UTC-4, Kowshik Prakasam wrote:The function below returns the local IP address if you give it a serverthat it should connect to. For example, you can pass "google.com:80"to the function.Is there a simpler way to find the local IP address? For example, withoutspecifying the port number in the server? In the code below, absenceof port number in the server raises an error.====================================================func getLocalIp(server string) (*string, error) {conn, err := net.Dial("udp", server)if err != nil {return nil, err}// conn.LocalAddr().String() returns ip_address:portreturn &strings.Split(conn.LocalAddr().String(), ":")[0], nil}====================================================-Kowshik
--
On Mon, Sep 24, 2012 at 9:03 PM, Steve McCoy <mcc...@gmail.com> wrote:I wrote a small program to print the host's external IPs: https://github.com/mccoyst/myip/blob/master/myip.goIt's been a while and I don't recall why I didn't use net.InterfaceAddrs(), though it actually seems like less programming effort than manually filtering out the loopbacks. However, I could be convinced that it'd be worth changing.
According to your program, my laptop's "external IP" (whatever that means) is 127.0.1.1.
It seems that your program obtains the hostname and attempts to resolve it. In general, the hostname may or may not resolve to an IP address, and even when it does, it may resolve to a loopback or a non-loopback IP address.
Here is another one which should list all IP addresses of a host (10 addresses on my laptop):
http://play.golang.org/p/Apqck0ovcr
Of course, it doesn't run on the playground, you have to copy it and run it locally.
Peter