| 1 |
#include <Rinternals.h> |
| 2 |
#include <stdlib.h> |
| 3 |
#include <string.h> |
| 4 |
|
| 5 |
#include <unistd.h> |
| 6 |
#include <fcntl.h> |
| 7 |
#include <errno.h> |
| 8 |
|
| 9 |
#ifdef _WIN32 |
| 10 |
#include <winsock2.h> |
| 11 |
#include <ws2tcpip.h> |
| 12 |
#else |
| 13 |
#include <sys/select.h> |
| 14 |
#include <sys/socket.h> |
| 15 |
#include <netinet/in.h> |
| 16 |
#include <netdb.h> |
| 17 |
#include <arpa/inet.h> |
| 18 |
#endif |
| 19 |
|
| 20 |
#ifdef _WIN32 |
| 21 |
static const char *formatError(DWORD res){ |
| 22 |
static char buf[1000], *p; |
| 23 |
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, |
| 24 |
NULL, res, |
| 25 |
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), |
| 26 |
buf, 1000, NULL); |
| 27 |
p = buf+strlen(buf) -1; |
| 28 |
if(*p == '\n') *p = '\0'; |
| 29 |
p = buf+strlen(buf) -1; |
| 30 |
if(*p == '\r') *p = '\0'; |
| 31 |
p = buf+strlen(buf) -1; |
| 32 |
if(*p == '.') *p = '\0'; |
| 33 |
return buf; |
| 34 |
} |
| 35 |
#define getsyserror() formatError(GetLastError()) |
| 36 |
#else |
| 37 |
#define getsyserror() strerror(errno) |
| 38 |
#endif |
| 39 |
|
| 40 |
|
| 41 |
static void syserror_if(int err, const char * what){ |
| 42 |
if(err) |
| 43 |
Rf_errorcall(R_NilValue, "System failure for: %s (%s)", what, getsyserror()); |
| 44 |
} |
| 45 |
|
| 46 |
static int port_is_available(int port){ |
| 47 |
|
| 48 |
|
| 49 |
struct sockaddr_in serv_addr; |
| 50 |
memset(&serv_addr, '0', sizeof(serv_addr)); |
| 51 |
serv_addr.sin_family = AF_INET; |
| 52 |
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); |
| 53 |
serv_addr.sin_port = htons(port); |
| 54 |
|
| 55 |
|
| 56 |
int sockfd = socket(AF_INET, SOCK_STREAM, 0); |
| 57 |
syserror_if(sockfd < 0, "socket()"); |
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
#ifndef _WIN32 |
| 62 |
int enable = 1; |
| 63 |
syserror_if(setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0, "SO_REUSEADDR"); |
| 64 |
#endif |
| 65 |
|
| 66 |
int res = bind(sockfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)); |
| 67 |
#ifdef _WIN32 |
| 68 |
closesocket(sockfd); |
| 69 |
#else |
| 70 |
close(sockfd); |
| 71 |
#endif |
| 72 |
return res == 0; |
| 73 |
} |
| 74 |
|
| 75 |
SEXP R_findport(SEXP candidates){ |
| 76 |
for(int i = 0; i < Rf_length(candidates); i++){ |
| 77 |
int port = INTEGER(candidates)[i]; |
| 78 |
if(port_is_available(port)){ |
| 79 |
return Rf_ScalarInteger(port); |
| 80 |
} |
| 81 |
} |
| 82 |
return R_NilValue; |
| 83 |
} |