Getting IP Address AND Hardware Address in golang...

3,813 views
Skip to first unread message

Curtis Paul

unread,
Dec 15, 2013, 4:30:02 AM12/15/13
to golan...@googlegroups.com
Any ideas on how to list all of the local IP Address and Hardware Addresses?

I understand the following, it provides Hardware Address...but the Interface struct does not provide IP Address.

interfaces, _ := net.Interfaces()
for _, inter := range interfaces {
        fmt.Println(inter.Name, inter.HardwareAddr)
}

Martin Schnabel

unread,
Dec 15, 2013, 4:50:35 AM12/15/13
to golan...@googlegroups.com
package main

import "fmt"
import "net"

func main() {
interfaces, _ := net.Interfaces()
for _, inter := range interfaces {
fmt.Println(inter.Name, inter.HardwareAddr)
fmt.Println(inter.Addrs())
}

}

Péter Szilágyi

unread,
Dec 15, 2013, 4:50:58 AM12/15/13
to Curtis Paul, golang-nuts
Hi,

  This should do it:

package main

import (
"fmt"
"net"
)

func main() {
interfaces, _ := net.Interfaces()
for _, inter := range interfaces {
fmt.Println(inter.Name, inter.HardwareAddr)
if addrs, err := inter.Addrs(); err == nil {
for _, addr := range addrs {
fmt.Println(inter.Name, "->", addr)
}
}
}
}

Output:
lo 
lo -> ::1/128
eth0 00:1e:ec:8b:f2:63
wlan0 00:16:ea:b5:e8:e0
wlan0 -> fe80::216:eaff:feb5:e8e0/64

Cheers,
  Peter

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Kevin Gillette

unread,
Dec 15, 2013, 4:51:48 AM12/15/13
to golan...@googlegroups.com
Each inter has an Addrs() method (see http://golang.org/pkg/net/#Interface.Addrs).

Michael Gehring

unread,
Dec 15, 2013, 4:51:58 AM12/15/13
to Curtis Paul, golan...@googlegroups.com
On Sun, Dec 15, 2013 at 01:30:02AM -0800, Curtis Paul wrote:
> Any ideas on how to list all of the local IP Address and Hardware Addresses?
>
> I understand the following, it provides Hardware Address...but the
> Interface struct does not provide IP Address.

http://golang.org/pkg/net/#Interface.Addrs

Curtis Paul

unread,
Dec 15, 2013, 1:03:54 PM12/15/13
to golan...@googlegroups.com
Péter's solution put it into perspective for me...


On Sunday, December 15, 2013 2:30:02 AM UTC-7, Curtis Paul wrote:

koti....@gmail.com

unread,
May 31, 2017, 9:26:15 AM5/31/17
to golang-nuts
How to set ip address to a given interface? is there any built-in function or reference implementation?
Reply all
Reply to author
Forward
0 new messages