NaviServer Programmable Web Server

ns_rand(n)

NaviServer Built-in Commands – 5.2.0a


[ Main Table Of Contents | Table Of Contents | Keyword Index ]

Name

ns_rand - Generate a random number

Table Of Contents

Synopsis

Description

This command generates a random number. If maximum is not specified, the random number returned is a floating-point value n such that 0.0 <= n < 1.0. If maximum is specified, it must be a positive integer between 1 and 2147483647, in which case ns_rand will return an integer value n such that 0 <= n <= max - 1. Internally ns_rand uses the NaviServer C API Ns_DRand. When OpenSSL support is compiled in, it uses OpenSSL's cryptographically secure random generator. Otherwise it uses arc4random() when available, followed by platform library generators (drand48(), random(), or rand()). The latter fallbacks do not provide cryptographic unpredictability. If OpenSSL random generation fails, an error is logged and the platform fallback is used. An internal random seed initializes the legacy generators at server startup.

COMMANDS

ns_rand ?maximum?

EXAMPLES

 % ns_rand
 0.39938485692
 % ns_rand 10
 7

CAVEAT

[ns_rand 1] will always produce the result 0. [ns_rand 2] will produce the desired "coin flip" outcome of 0 or 1. This is standard with Java's java.util.Random implementation of nextInt and most other random number libraries.

The function ns_crypto::randombytes returns high quality random values based on the OpenSSL random implementation.

See Also

ns_crypto, nsd

Keywords

global built-in, random