20 #if defined(MRPT_OS_LINUX) || defined(__APPLE__) 21 #define INVALID_SOCKET (-1) 23 #include <sys/socket.h> 27 #include <sys/types.h> 28 #include <sys/ioctl.h> 30 #include <arpa/inet.h> 31 #include <netinet/in.h> 45 unsigned short listenPort,
const std::string& IPaddress,
46 int maxConnectionsWaiting)
57 sockaddr_in desiredIP;
59 desiredIP.sin_family = AF_INET;
60 desiredIP.sin_addr.s_addr = inet_addr(IPaddress.c_str());
61 desiredIP.sin_port = htons((
unsigned short)listenPort);
64 ::bind(
m_serverSock, (
struct sockaddr*)(&desiredIP),
sizeof(desiredIP)))
69 if (INVALID_SOCKET == listen(
m_serverSock, maxConnectionsWaiting))
74 "[CServerTCPSocket] Listening at %s:%i\n", IPaddress.c_str(),
93 struct timeval timeoutSelect;
94 struct timeval* ptrTimeout;
104 ptrTimeout =
nullptr;
108 timeoutSelect.tv_sec = timeout_ms / 1000;
109 timeoutSelect.tv_usec = 1000 * (timeout_ms % 1000);
110 ptrTimeout = &timeoutSelect;
114 MRPT_LOG_DEBUG(
"[CServerTCPSocket::accept] Waiting incoming connections");
116 int selRet = ::select(
123 if (selRet == INVALID_SOCKET)
132 "[CServerTCPSocket::accept] Timeout waiting incoming " 141 "[CServerTCPSocket::accept] Incoming connection accepted\n");
145 sockaddr_in otherPart;
146 socklen_t otherPartSize =
sizeof(otherPart);
149 m_serverSock, (
struct sockaddr*)&otherPart, &otherPartSize);
151 if (aceptdSock == INVALID_SOCKET)
154 return std::unique_ptr<CClientTCPSocket>();
157 auto ret = std::make_unique<CClientTCPSocket>();
159 ret->m_hSock = aceptdSock;
161 ret->m_remotePartIP =
std::string(inet_ntoa(otherPart.sin_addr));
162 ret->m_remotePartPort = ntohs(otherPart.sin_port);
165 "[CServerTCPSocket::accept] Connection accepted from %s:%u\n",
166 ret->m_remotePartIP.c_str(), ret->m_remotePartPort);
#define MRPT_LOG_DEBUG(_STRING)
Use: MRPT_LOG_DEBUG("message");
#define MRPT_LOG_ERROR_FMT(_FMT_STRING,...)
#define THROW_EXCEPTION(msg)
std::string getLastSocketErrorStr()
Returns a description of the last Sockets error.
std::string getLastErrorStr()
Returns a description of the last Sockets error.
unsigned int m_serverSock
The handle for the listening server TCP socket.
std::unique_ptr< CClientTCPSocket > accept(int timeout_ms=-1)
Waits for an incoming connection (indefinitely, or with a given timeout) The returned object represen...
void setupSocket(unsigned short listenPort, const std::string &IPaddress, int maxConnectionsWaiting)
Common code called from the platform-dependant constructor.
#define MRPT_LOG_DEBUG_FMT(_FMT_STRING,...)
Use: MRPT_LOG_DEBUG_FMT("i=%u", i);
GLsizei const GLchar ** string
int fprintf(FILE *fil, const char *format,...) noexcept MRPT_printf_format_check(2
An OS-independent version of fprintf.
std::string format(const char *fmt,...) MRPT_printf_format_check(1
A std::string version of C sprintf.
bool isListening()
Returns true if the socket was successfully open and it's bound to the desired port.
#define MRPT_LOG_WARN(_STRING)
Serial and networking devices and utilities.