Reading from /dev/random

In this section, you will learn how to read from the /dev/random system device. The purpose of the /dev/random system device is to generate random data, which you might use for testing your programs or, in this case, you will plant the seed for a random number generator. Getting data from /dev/random can be a little bit tricky, and this is the main reason for specifically discussing it here.

On a macOS High Sierra machine, the /dev/random file has the following permissions:

$ ls -l /dev/random
crw-rw-rw-  1 root  wheel   14,   0 Jan  8 20:24 /dev/random

Similarly, on a Debian Linux machine, the /dev/random system device has the following Unix file permissions:

$ ls -l /dev/random
crw-rw-rw- 1 root root 1, 8 Jan 13 12:19 /dev/random

This means that the /dev/random file has analogous file permissions on both Unix variants. The only difference between these two Unix variants is the group that owns the file, which is wheel on macOS and root on Debian Linux, respectively.

The name of the program for this topic is devRandom.go, and it will be presented in three parts. The first part of the program is as follows:

package main 
 
import ( 
    "encoding/binary" 
    "fmt" 
    "os" 
) 

In order to read from /dev/random, you will need to import the encoding/binary standard Go package, because /dev/random returns binary data that needs to be decoded.

The second code portion of devRandom.go follows next:

func main() { 
    f, err := os.Open("/dev/random") 
    defer f.Close() 
 
    if err != nil { 
        fmt.Println(err) 
        return 
    } 

You open /dev/random as usual because everything in Unix is a file.

The last code segment of devRandom.go is shown in the following Go code:

    var seed int64 
    binary.Read(f, binary.LittleEndian, &seed) 
    fmt.Println("Seed:", seed) 
} 

You need the binary.Read() function, which requires three parameters, in order to read from the /dev/random system device. The value of the second parameter (binary.LittleEndian) specifies that you want to use the little endian byte order. The other option is binary.BigEndian, which is used when your computer is using the big endian byte order.

Executing devRandom.go will generate the following type of output:

$ go run devRandom.go
Seed: -2044736418491485077
$ go run devRandom.go
Seed: -5174854372517490328
$ go run devRandom.go
Seed: 7702177874251412774
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.66.156