| 1 | #' Random Port |
| 2 | #' |
| 3 | #' Generate a valid, random TCP port. |
| 4 | #' |
| 5 | #' By definition, a TCP port is an unsigned short, and so it can not |
| 6 | #' exceed 65535. Additionally, ports in the range 1024 to 49151 are |
| 7 | #' (possibly) registered by ICANN for specific uses. |
| 8 | #' |
| 9 | #' \code{random_port()} will simply generate a valid, non-registered |
| 10 | #' tcp port. \code{random_unused_port()} will generate a port |
| 11 | #' that is available for socket connections. |
| 12 | #' |
| 13 | #' \code{random_open_port()} finds a random port not already bound |
| 14 | #' to an endpoint. |
| 15 | #' |
| 16 | #' @param min_port,max_port |
| 17 | #' The minimum/maximum value to be generated. The minimum should not |
| 18 | #' be below 49152 and the maximum should not exceed 65536 (see |
| 19 | #' details). |
| 20 | #' @param max_tries |
| 21 | #' The maximum number of times a random port will be searched for. |
| 22 | #' |
| 23 | #' @references |
| 24 | #' "The Ephemeral Port Range" by Mike Gleason. |
| 25 | #' \url{https://www.ncftp.com/ncftpd/doc/misc/ephemeral_ports.html} |
| 26 | #' |
| 27 | #' @author Drew Schmidt |
| 28 | #' |
| 29 | #' @examples |
| 30 | #' random_port() |
| 31 | #' |
| 32 | #' @importFrom stats runif |
| 33 | #' |
| 34 | #' @rdname random_port |
| 35 | #' @export |
| 36 | random_port <- function(min_port=49152, max_port=65536) |
| 37 | { |
| 38 | if (min_port < 49152) |
| 39 | warning("non-recommended 'min_port' value; see ?random_port for details") |
| 40 | if (max_port > 65536) |
| 41 | warning("non-recommended 'max_port' value; see ?random_port for details") |
| 42 | |
| 43 | |
| 44 | as.integer(runif(1, min_port, max_port+1)) |
| 45 | } |
| 46 | |
| 47 | |
| 48 | |
| 49 | #' @rdname random_port |
| 50 | #' @export |
| 51 | random_open_port <- function(min_port=49152, max_port=65536, max_tries=100) |
| 52 | { |
| 53 | ctxt <- init.context() |
| 54 | socket <- init.socket(ctxt, "ZMQ_REP") |
| 55 | |
| 56 | ret <- -1 |
| 57 | |
| 58 | for (i in 1:max_tries) |
| 59 | { |
| 60 | port <- random_port(min_port=min_port, max_port=max_port) |
| 61 | addr <- paste0("tcp://*:", port) |
| 62 | |
| 63 | catch <- tryCatch(zmq.bind(socket, addr), error=identity, warning=identity) |
| 64 | if (!inherits(catch, "error") && !inherits(catch, "warning")) |
| 65 | { |
| 66 | ret <- port |
| 67 | break |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | rm(socket);rm(ctxt); |
| 72 | invisible(gc()) |
| 73 | |
| 74 | if (ret == -1) |
| 75 | stop("No valid port could be found.") |
| 76 | else |
| 77 | return(ret) |
| 78 | } |