Golang : Check whether a network interface is up on your machine
Problem:
You have multiple network interfaces on your machine and you need to know the status of a particular network interface is actually up before routing command to it.
Solution:
The code example that follows will use the net
package's InterfaceByName()
function to probe the interface status for a given interface name. If the given network interface is not available, the program will list out the available network interfaces.
Here you go!
package main
import (
"fmt"
"net"
"os"
"strings"
)
func availableInterfaces() {
interfaces, err := net.Interfaces()
if err != nil {
fmt.Print(err)
os.Exit(0)
}
fmt.Println("Available network interfaces on this machine : ")
for _, i := range interfaces {
fmt.Printf("Name : %v \n", i.Name)
}
}
func main() {
if len(os.Args) != 2 {
fmt.Printf("Usage : %s <interface name>\n", os.Args[0])
os.Exit(0)
}
ifName := os.Args[1]
byNameInterface, err := net.InterfaceByName(ifName)
if err != nil {
fmt.Println(err, "["+ifName+"]")
fmt.Println("-----------------------------")
availableInterfaces()
os.Exit(0)
}
if strings.Contains(byNameInterface.Flags.String(), "up") {
fmt.Println("Status : UP")
} else {
fmt.Println("Status : DOWN")
}
}
Sample output for my own machine. Your machine will show different results.
$ ./getifacestatus stf0
Status : DOWN
$ ./getifacestatus en3
Status : UP
$ ./getifacestatus eth0
route ip+net: no such network interface [eth0]
-----------------------------
Available network interfaces on this machine :
Name : lo0
Name : gif0
Name : stf0
Name : en3
References:
See also : Golang : Get the IPv4 and IPv6 addresses for a specific network interface
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+5.3k Gogland : Datasource explorer
+11.9k Golang : Split strings into command line arguments
+47.7k Golang : How to convert JSON string to map and slice
+7.4k Golang : Mapping Iban to Dunging alphabets
+11.5k Golang : GTK Input dialog box examples
+5.8k AWS S3 : Prevent Hotlinking policy
+13.8k Golang : Fix cannot use buffer (type bytes.Buffer) as type io.Writer(Write method has pointer receiver) error
+7.3k Golang : How to stop user from directly running an executable file?
+6.6k Unix/Linux : How to fix CentOS yum duplicate glibc or device-mapper-libs dependency error?
+7.3k Golang : How to handle file size larger than available memory panic issue
+24.2k Golang : Time slice or date sort and reverse sort example
+19.6k Golang : Append content to a file