-
-
Save jniltinho/9787946 to your computer and use it in GitHub Desktop.
package main | |
/* | |
URL: https://github.com/mccoyst/myip/blob/master/myip.go | |
URL: http://changsijay.com/2013/07/28/golang-get-ip-address/ | |
*/ | |
import ( | |
"net" | |
"os" | |
) | |
func main() { | |
addrs, err := net.InterfaceAddrs() | |
if err != nil { | |
os.Stderr.WriteString("Oops: " + err.Error() + "\n") | |
os.Exit(1) | |
} | |
for _, a := range addrs { | |
if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { | |
if ipnet.IP.To4() != nil { | |
os.Stdout.WriteString(ipnet.IP.String() + "\n") | |
} | |
} | |
} | |
} |
Thanks, This helps a lot!
i want explanation of this code
Thanks, This helps a lot!
Thanks
Thanks, good work
Might be easier to do something like this:
package main
import "net"
func main() {
conn, err := net.Dial("udp", "8.8.8.8:80")
// handle err...
defer conn.Close()
localAddr := conn.LocalAddr().(*net.UDPAddr)
}
This will give you the primary IP address used by your system (great for machines that have multiple ips, interfaces etc).
Also, you can use the netFlags to determine the status and capabilities of that interface which could be very useful.
@rucuriousyet Could I use 1.2.3.4:1 to dial udp.
@jniltinho thanks it worked for me :)
@rucuriousyet in my case i have 2 addresses on same interface i think your solution will get only one of them....
Can someone explain line 21, didnt got the a.(*net.IPNet)
.
Thanks
Might be easier to do something like this:
package main import "net" func main() { conn, err := net.Dial("udp", "8.8.8.8:80") // handle err... defer conn.Close() localAddr := conn.LocalAddr().(*net.UDPAddr) }This will give you the primary IP address used by your system (great for machines that have multiple ips, interfaces etc).
China cannot access google dns 8.8.8.8
Might be easier to do something like this:
package main import "net" func main() { conn, err := net.Dial("udp", "8.8.8.8:80") // handle err... defer conn.Close() localAddr := conn.LocalAddr().(*net.UDPAddr) }This will give you the primary IP address used by your system (great for machines that have multiple ips, interfaces etc).
China cannot access google dns
8.8.8.8
Does not matter, its a UDP connection therefore there is no handshake, works offline
Thanks! very simple and powerful!
Thanks! very simple and powerful!
牛批的很
just thank you very much.