Generate MAC address in Go

huangapple go评论94阅读模式
英文:

Generate MAC address in Go

问题

我正在寻找一个在Go语言中生成MAC地址的示例。我找到了很多关于创建UUID的示例,但没有关于MAC地址的。

有人可以帮忙吗?

谢谢,
Ben

英文:

I'm looking for an example on how to generate a MAC Address in Go.
I have found many examples on creating UUIDs but nothing on MAC addresses.

Can someone help?

Thanks,
Ben

答案1

得分: 15

这是我会做的方式(playground

import (
	"crypto/rand"
	"fmt"
)

func main() {
	buf := make([]byte, 6)
	_, err := rand.Read(buf)
	if err != nil {
		fmt.Println("错误:", err)
		return
	}
	// 设置本地位
	buf[0] |= 2
	fmt.Printf("随机MAC地址:%02x:%02x:%02x:%02x:%02x:%02x\n", buf[0], buf[1], buf[2], buf[3], buf[4], buf[5])
}

请注意设置本地位,这意味着它不会与任何全局管理的地址冲突(详见维基百科了解更多信息

英文:

Here is how I would do it (playground)

import (
	"crypto/rand"
	"fmt"
)

func main() {
	buf := make([]byte, 6)
	_, err := rand.Read(buf)
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	// Set the local bit
	buf[0] |= 2
	fmt.Printf("Random MAC address: %02x:%02x:%02x:%02x:%02x:%02x\n", buf[0], buf[1], buf[2], buf[3], buf[4], buf[5])
}

Note the setting of the local bit which means it won't clash with any globally administered addresses (see wikipedia for more info)

huangapple
  • 本文由 发表于 2014年1月9日 19:19:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/21018729.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定