19 #if defined(MRPT_OS_LINUX) || defined(MRPT_OS_APPLE)
20 #define INVALID_SOCKET (-1)
22 #include <sys/socket.h>
26 #include <sys/types.h>
27 #include <sys/ioctl.h>
29 #include <arpa/inet.h>
30 #include <netinet/in.h>
33 #ifdef MRPT_OS_WINDOWS
35 typedef int socklen_t;
44 unsigned short listenPort,
const std::string& IPaddress,
45 int maxConnectionsWaiting)
56 sockaddr_in desiredIP;
58 desiredIP.sin_family = AF_INET;
59 desiredIP.sin_addr.s_addr = inet_addr(IPaddress.c_str());
60 desiredIP.sin_port = htons((
unsigned short)listenPort);
63 ::bind(
m_serverSock, (
struct sockaddr*)(&desiredIP),
sizeof(desiredIP)))
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(
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);
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_WARN(_STRING)
#define MRPT_LOG_DEBUG_FMT(_FMT_STRING,...)
#define MRPT_LOG_DEBUG(_STRING)
#define MRPT_LOG_ERROR_FMT(_FMT_STRING,...)
bool isListening()
Returns true if the socket was successfully open and it's bound to the desired port.
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.
std::string getLastErrorStr()
Returns a description of the last Sockets error.
int m_serverSock
The handle for the listening server TCP socket.
GLsizei const GLchar ** string
std::string getLastSocketErrorStr()
Returns a description of the last Sockets error.
int fprintf(FILE *fil, const char *format,...) noexcept MRPT_printf_format_check(2
An OS-independent version of fprintf.
#define THROW_EXCEPTION(msg)
Serial and networking devices and utilities.
std::string format(const char *fmt,...) MRPT_printf_format_check(1
A std::string version of C sprintf.