記錄一下用mac地址+local時間作為seed來產生隨機數
// 首先記錄一下rand.Seed()怎么用 // 官方說明,傳入int64數據為Seed func (r *Rand) Seed(seed int64) // Seed uses the provided seed value to initialize the generator to a deterministic state. // Seed使用提供的seed值將發生器初始化為確定性狀態。 導致每次rand出來的都是一樣的,所以至少我要加入時間戳為隨機數種子
// 獲取時間戳函數使用示例 t1 := time.Now().Unix() // 單位s,打印結果:1491888244 t2 := time.Now().UnixNano() // 單位納秒,打印結果: // output 精度的差別 1491888244752784461 type:int64
完整代碼:
package main import ( "fmt" "net" "time" "hash/fnv" ) /* 加密 encryption */ // net func GetMacAddrs()(string,error){ netInterfaces, err := net.Interfaces() if err != nil { return "",err } for _, netInterface := range netInterfaces { macAddr := netInterface.HardwareAddr.String() if len(macAddr) == 0 { continue } return macAddr,nil } return "",err } // hash output uint32 func Hash(s string) uint32{ h := fnv.New32a() h.Write([]byte(s)) return h.Sum32() } // add mac and time.now() as seed func Hashseed() int64{ mac_adr, _ := GetMacAddrs() t := time.Now().UnixNano() // int64 return int64(Hash(fmt.Sprintf("%d %s",t,mac_adr))) } func main(){ rand.Seed(Hashseed()) rnd := make([]byte,4) binary.LittleEndian.PutUint32(rnd, rand.Uint32()) fmt.Println(rnd) }