go 操作mac

cilium 1.15.1

MAC地址的长度是48位(6个字节),表示为12个16进制数,例如00:01:02:03:04:05。

生成随机mac

package main

import (
	"crypto/rand"
	"fmt"
	"net"
)

// MAC address is an net.HardwareAddr encapsulation to force cilium to only use MAC-48.
type MAC net.HardwareAddr

// String returns the string representation of m.
func (m MAC) String() string {
	return net.HardwareAddr(m).String()
}

// GenerateRandMAC generates a random unicast and locally administered MAC address.
func GenerateRandMAC() (MAC, error) {
	buf := make([]byte, 6)
	if _, err := rand.Read(buf); err != nil {
		return nil, fmt.Errorf("Unable to retrieve 6 rnd bytes: %s", err)
	}

	// Set locally administered addresses bit and reset multicast bit
	buf[0] = (buf[0] | 0x02) & 0xfe

	return buf, nil
}

func main() {
	if mac, err := GenerateRandMAC(); err == nil {
		fmt.Println(mac)
	}
	if mac, err := GenerateRandMAC(); err == nil {
		fmt.Println(mac)
	}
}

根据ipv4地址生成mac

前面4位固定是06:06。

package main

import "fmt"

func main() {
	// ipv4地址是100.101.102.15
	fmt.Println(fmt.Sprintf("06:06:%02x:%02x:%02x:%02x", 100, 101, 102, 15))
}

posted on 2024-06-08 11:05  王景迁  阅读(10)  评论(0编辑  收藏  举报

导航