Golang中mac地址+時間戳加入rand.Seed()產生隨機數


記錄一下用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)

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM