39 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX 40 #include <arpa/inet.h> 46 #if defined(__MINGW32__) 47 #define _WIN32_WINNT _WIN32_WINNT_VISTA // 0x0600 52 #include <visp3/core/vpUDPClient.h> 61 : m_serverAddress(), m_serverLength(0), m_socketFileDescriptor()
72 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX 73 close(m_socketFileDescriptor);
75 closesocket(m_socketFileDescriptor);
80 void vpUDPClient::init(
const std::string &hostname,
const int port)
83 if (WSAStartup(MAKEWORD(2, 2), &m_wsa) != 0) {
85 ss <<
"Failed WSAStartup for the server, error code: " << WSAGetLastError();
91 m_socketFileDescriptor = socket(AF_INET, SOCK_DGRAM, 0);
93 if (m_socketFileDescriptor == INVALID_SOCKET)
95 if (m_socketFileDescriptor < 0)
100 memset(&m_serverAddress, 0,
sizeof(m_serverAddress));
101 std::stringstream ss;
103 struct addrinfo hints;
104 struct addrinfo *result = NULL;
105 struct addrinfo *ptr = NULL;
107 memset(&hints, 0,
sizeof(hints));
108 hints.ai_family = AF_INET;
109 hints.ai_socktype = SOCK_DGRAM;
110 hints.ai_protocol = IPPROTO_UDP;
112 DWORD dwRetval = getaddrinfo(hostname.c_str(), ss.str().c_str(), &hints, &result);
115 ss <<
"getaddrinfo failed with error: " << dwRetval;
119 for (ptr = result; ptr != NULL; ptr = ptr->ai_next) {
120 if (ptr->ai_family == AF_INET && ptr->ai_socktype == SOCK_DGRAM) {
121 m_serverAddress = *(
struct sockaddr_in *)ptr->ai_addr;
126 freeaddrinfo(result);
128 m_serverLength =
sizeof(m_serverAddress);
157 FD_SET(m_socketFileDescriptor, &s);
158 struct timeval timeout;
160 timeout.tv_sec = timeoutMs / 1000;
161 timeout.tv_usec = (timeoutMs % 1000) * 1000;
163 int retval = select((
int)m_socketFileDescriptor + 1, &s, NULL, NULL, timeoutMs > 0 ? &timeout : NULL);
166 std::cerr <<
"Error select!" << std::endl;
172 int length = recvfrom(m_socketFileDescriptor, m_buf,
sizeof(m_buf), 0, (
struct sockaddr *)&m_serverAddress,
173 (socklen_t *)&m_serverLength);
175 return length < 0 ? -1 : 0;
178 msg = std::string(m_buf, length);
213 if (msg.size() > VP_MAX_UDP_PAYLOAD) {
214 std::cerr <<
"Message is too long!" << std::endl;
219 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX 220 return sendto(m_socketFileDescriptor, msg.c_str(), msg.size(), 0, (
struct sockaddr *)&m_serverAddress,
223 return sendto(m_socketFileDescriptor, msg.c_str(), (int)msg.size(), 0, (
struct sockaddr *)&m_serverAddress,
int receive(std::string &msg, const int timeoutMs=0)
error that can be emited by ViSP classes.
vpUDPClient(const std::string &hostname, const int port)
int send(const std::string &msg)