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

Possible alternative method #3

Open
hrbrmstr opened this issue Jan 31, 2020 · 0 comments
Open

Possible alternative method #3

hrbrmstr opened this issue Jan 31, 2020 · 0 comments

Comments

@hrbrmstr
Copy link
Contributor

hrbrmstr commented Jan 31, 2020

The {ps} package provides a means to get LISTENING port info in a cross-platform way. e.g.

library(ps)

lapply(ps()$ps_handle, function(x) {
  tryCatch(ps_connections(x), error=function(x) NULL) # more on the need for this after the code block
}) -> res

res <- res[lengths(res) > 0] # some return values of `ps_connections()` are non-existent
res <- res[sapply(res, nrow) > 0] # and some are empty data frames
res <- do.call(rbind.data.frame, res) # now make a df
res <- res[which((res$family %in% c("AF_INET", "AF_INET6")) & (res$state == "CONN_LISTEN")),] # and focus on network things

sort(res$lport)
##  [1]  2600  3283  6000  6000  6372  7473  7474  7687  9222  9222 11199 11781 16662 
## [24] 17500 17500 17600 17603 25757 26482 26510 49162 49162 49202 49282 49282 49313

Unlike netstat, R is not "blessed" by the OS (certain systems, like macOS, make exceptions for some longstanding utilities) so R doesn't have default permissions to get LISTENING ports like netstat does without help.

Running the same thing with an R session started with sudo the same code above returns the following on my currently running system:

##  [1]    22    22    22    22    88    88   111   111   445   445   445   445
## [13]   996   999  1012  1017  1019  1021  1022  1023  2049  2049  2600  3031
## [25]  3031  3031  3031  3283  4502  5900  5900  5900  5900  6000  6000  6372
## [37]  7473  7474  7687  9222  9222 11199 11781 16662 17500 17500 17600 17603
## [49] 25757 26482 26510 49162 49162 49202 49282 49282 49313 49347 63202 63202

Granted, that's more painful than relying on netstat's blessed behavior, but it alleviates the need to parse netstat output in other locales and might be a useful alternative function.

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

No branches or pull requests

1 participant