Home > Article > Backend Development > A brief analysis of how to set up a network card in Go language
Go is a cross-platform programming language with a powerful network programming library that can meet various network programming needs. In practical applications, we often need to control the network interface, such as setting the network card IP address, MAC address, etc. This article will introduce how to set up the network card using Go language.
In Go language, you can get all the network card information in the system through the net.Interface
structure. Below is a simple sample code that prints out the names and MAC addresses of all network cards in the system.
package main import ( "fmt" "net" ) func main() { interfaces, err := net.Interfaces() if err != nil { panic(err) } for _, itf := range interfaces { fmt.Printf("Name: %s\n", itf.Name) fmt.Printf("MAC address: %s\n", itf.HardwareAddr) } }
To set the network card IP address you need to use InterfaceAddrs()
and # in the net
library ##ParseCIDR()Method. Below is a simple example code to set the IP address of network card en0 to 192.168.1.100/24.
package main import ( "fmt" "net" ) func main() { iface, err := net.InterfaceByName("en0") if err != nil { panic(err) } addr, err := net.ParseCIDR("192.168.1.100/24") if err != nil { panic(err) } err = iface.Addrs() if err != nil { panic(err) } err = netlink.AddrAdd(iface, addr) if err != nil { panic(err) } fmt.Println("IP address set successfully") }
SetHardwareAddr() method in the
netlink library. Below is a simple example code to set the MAC address of network card en0 to 00:11:22:33:44:55.
package main import ( "fmt" "net" "github.com/vishvananda/netlink" ) func main() { iface, err := net.InterfaceByName("en0") if err != nil { panic(err) } link, err := netlink.LinkByName(iface.Name) if err != nil { panic(err) } macAddr, err := net.ParseMAC("00:11:22:33:44:55") if err != nil { panic(err) } err = netlink.LinkSetHardwareAddr(link, macAddr) if err != nil { panic(err) } fmt.Println("MAC address set successfully") }
The above is the detailed content of A brief analysis of how to set up a network card in Go language. For more information, please follow other related articles on the PHP Chinese website!