Getting the IPv4 address of a network interface

873 views
Skip to first unread message

chris...@gmail.com

unread,
Mar 21, 2014, 4:04:45 PM3/21/14
to golan...@googlegroups.com
Given a network interface (e.g. "eth0"), I'm trying to determine it's IPv4 address.

I can test an IP to see if it's IPv4 with net.IP.DefaultMask() but I'm unable to do this the results of net.Interfaces() because that returns an []Interface struct (from which I can extract an []Addr) and what I need is a net.IP:


I think doing regex on the interface address would be too ugly.

How can I convert a type Addr to a type IP?

Thanks.

Taru Karttunen

unread,
Mar 21, 2014, 4:23:50 PM3/21/14
to chris...@gmail.com, golan...@googlegroups.com
switch x := myaddr.(type) {
case *net.IPNet:
...
}

- Taru Karttunen

chris...@gmail.com

unread,
Mar 21, 2014, 5:24:47 PM3/21/14
to golan...@googlegroups.com, chris...@gmail.com
On Friday, March 21, 2014 1:23:50 PM UTC-7, Taru Karttunen wrote:

switch x := myaddr.(type) {
case *net.IPNet:
...
}

Thanks, Taru.  For the record, here's how I used your hint to solve this:


Chris 

Mikio Hara

unread,
Mar 22, 2014, 4:32:54 AM3/22/14
to chris...@gmail.com, golang-nuts
On Sat, Mar 22, 2014 at 6:24 AM, <chris...@gmail.com> wrote:

> http://play.golang.org/p/SA5nvAipdF

I'd prefer to use net.IP.To4 for testing; for example,
http://golang.org/src/pkg/net/interface_test.go#L31
Reply all
Reply to author
Forward
0 new messages