Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WISH: Make serverSocket(0) useful (+ find a random TCP port that can be listened to) #158

Open
HenrikBengtsson opened this issue Jan 5, 2024 · 1 comment
Labels

Comments

@HenrikBengtsson
Copy link
Owner

HenrikBengtsson commented Jan 5, 2024

In many situations, it's useful to be able to identify a "free" TCP port, i.e. a port that we can bind to.

CORRECTION +30 min: serverSocket() would only validate that we can listen to the port. To assert we can bind to it, we would have to do more. I need ☕

In R (>= 4.0.0), we can almost use serverSocket(0) for this. It will open a servsockconn connection on a random TCP port assigned to us by the operating system. This works on Linux, macOS, and MS Windows. For example,

> con <- serverSocket(port = 0L)

> print(con)
A connection with                          
description "localhost"   
class       "servsockconn"
mode        "a+"          
text        "text"        
opened      "opened"      
can read    "yes"         
can write   "yes"  

> str(con)
 'servsockconn' int 3
 - attr(*, "conn_id")=<externalptr> 

However, this is currently a useless connection, because we do not know which port is used here.

Wish

  • Add a function to query the port of a servsockconn connection, e.g. port(con).

This would make it possible to use the above servsockconn connection as-is, but it would also make it possible to find a random available TCP port, e.g.

find_available_tcp_port <- function() {
  con <- serverSocket(port = 0L)
  on.exit(close(con))
  port(con)
}

References

cc/ @noamross

@HenrikBengtsson HenrikBengtsson changed the title WISH: Find a TCP port that can be bound ("opened") + make serverSocket(0) useful WISH: Make serverSocket(0) useful (+ find a random TCP port that can be listened to) Jan 5, 2024
@shikokuchuo
Copy link

You can do this already using the equivalent in {nanonext}, but agree it would be nice for base R to have this.

find_available_tcp_port <- function() {
  s <- nanonext::socket(listen = "tcp://127.0.0.1:0")
  on.exit(close(s))
  nanonext::opt(s$listener[[1L]], "tcp-bound-port")
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants