Net interfaces

This is an example Go program for net-interfaces/.

package main

import (
        "fmt"
        "net"
        "os"
)

func main() {
        interfaces, err := net.Interfaces()
        if err != nil {
                fmt.Fprint(os.Stderr, "Error calling net.Interfaces(): %s\n", err)
                return
        }
        for _, i := range interfaces {
                fmt.Printf("Interface %d is '%s', MTU: %d; address: %s; flags: %s\n",
                        i.Index, i.Name, i.MTU, i.HardwareAddr, i.Flags)
                addrs, err := i.Addrs()
                if err != nil {
                        fmt.Fprintf(os.Stderr, "Error getting address: %s\n", err)
                        continue
                }
                for _, a := range addrs {
                        fmt.Printf("Network: %s; Address: %s\n", a.Network(),
                                a.String())
                }
        }
}

(download)

The output of the example looks like this:

Interface 1 is 'em0', MTU: 1500; address: XX:XX:XX:XX:XX:a8; flags: up|broadcast|multicast
Network: ip+net; Address: XXX.XXX.X.2/24
Interface 2 is 'em1', MTU: 1500; address: XX:XX:XX:XX:XX:49; flags: broadcast|multicast
Interface 3 is 'lo0', MTU: 16384; address: ; flags: up|loopback|multicast
Network: ip+net; Address: ::1/128
Network: ip+net; Address: XXXX::1/64
Network: ip+net; Address: XXX.X.X.1/8

Here some of the actual numbers have been replaced with Xs.


Copyright © Ben Bullock 2009-2023. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com) or use the discussion group at Google Groups. / Privacy / Disclaimer