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)

}

 

posted @ 2018-12-21 18:21  kumata  阅读(3696)  评论(0编辑  收藏  举报