go生成随机mac

hellsam · · 1630 次点击
``` package main import ( "fmt" "math/rand" "time" ) type Mac [6]byte func (m Mac) String() string { return fmt.Sprintf("%02x:%02x:%02x:%02x:%02x:%02x",m[0],m[1],m[2],m[3],m[4],m[5]) } func NewRandomMac() Mac{ var m [6]byte rand.Seed(time.Now().UnixNano()) for i:=0;i<6;i++ { mac_byte := rand.Intn(256) m[i] = byte(mac_byte) rand.Seed(int64(mac_byte)) } return Mac(m) } func main() { fmt.Println(NewRandomMac()) } ```
#4
更多评论
buscoop
纸上得来终觉浅,绝知此事要躬行!
<pre> 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]) } </pre>
#1
buscoop
纸上得来终觉浅,绝知此事要躬行!
``` go 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]) } ```
#2