20 #if defined(MRPT_OS_LINUX) || defined(__APPLE__) 21 #define INVALID_SOCKET (-1) 23 #include <arpa/inet.h> 26 #include <netinet/in.h> 27 #include <sys/ioctl.h> 28 #include <sys/socket.h> 29 #include <sys/types.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))
73 "[CServerTCPSocket] Listening at %s:%i\n", IPaddress.c_str(),
92 struct timeval timeoutSelect;
93 struct timeval* ptrTimeout;
103 ptrTimeout =
nullptr;
107 timeoutSelect.tv_sec = timeout_ms / 1000;
108 timeoutSelect.tv_usec = 1000 * (timeout_ms % 1000);
109 ptrTimeout = &timeoutSelect;
113 MRPT_LOG_DEBUG(
"[CServerTCPSocket::accept] Waiting incoming connections");
115 int selRet = ::select(
122 if (selRet == INVALID_SOCKET)
131 "[CServerTCPSocket::accept] Timeout waiting incoming " 140 "[CServerTCPSocket::accept] Incoming connection accepted\n");
144 sockaddr_in otherPart;
145 socklen_t otherPartSize =
sizeof(otherPart);
148 m_serverSock, (
struct sockaddr*)&otherPart, &otherPartSize);
150 if (aceptdSock == INVALID_SOCKET)
153 return std::unique_ptr<CClientTCPSocket>();
156 auto ret = std::make_unique<CClientTCPSocket>();
158 ret->m_hSock = aceptdSock;
160 ret->m_remotePartIP = std::string(inet_ntoa(otherPart.sin_addr));
161 ret->m_remotePartPort = ntohs(otherPart.sin_port);
164 "[CServerTCPSocket::accept] Connection accepted from %s:%u\n",
165 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 std::string format(std::string_view fmt, ARGS &&... args)
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);
int fprintf(FILE *fil, const char *format,...) noexcept MRPT_printf_format_check(2
An OS-independent version of fprintf.
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.