39 #include <visp3/core/vpConfig.h> 42 #ifdef VISP_HAVE_FUNC_INET_NTOP 44 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX 45 #include <arpa/inet.h> 51 #if defined(__MINGW32__) 53 # define _WIN32_WINNT _WIN32_WINNT_VISTA // 0x0600 59 #include <visp3/core/vpUDPClient.h> 68 : m_serverAddress(), m_serverLength(0), m_socketFileDescriptor()
79 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX 80 close(m_socketFileDescriptor);
82 closesocket(m_socketFileDescriptor);
87 void vpUDPClient::init(
const std::string &hostname,
const int port)
90 if (WSAStartup(MAKEWORD(2, 2), &m_wsa) != 0) {
92 ss <<
"Failed WSAStartup for the server, error code: " << WSAGetLastError();
98 m_socketFileDescriptor = socket(AF_INET, SOCK_DGRAM, 0);
100 if (m_socketFileDescriptor == INVALID_SOCKET)
102 if (m_socketFileDescriptor < 0)
107 memset(&m_serverAddress, 0,
sizeof(m_serverAddress));
108 std::stringstream ss;
110 struct addrinfo hints;
111 struct addrinfo *result = NULL;
112 struct addrinfo *ptr = NULL;
114 memset(&hints, 0,
sizeof(hints));
115 hints.ai_family = AF_INET;
116 hints.ai_socktype = SOCK_DGRAM;
117 hints.ai_protocol = IPPROTO_UDP;
119 DWORD dwRetval = getaddrinfo(hostname.c_str(), ss.str().c_str(), &hints, &result);
122 ss <<
"getaddrinfo failed with error: " << dwRetval;
126 for (ptr = result; ptr != NULL; ptr = ptr->ai_next) {
127 if (ptr->ai_family == AF_INET && ptr->ai_socktype == SOCK_DGRAM) {
128 m_serverAddress = *(
struct sockaddr_in *)ptr->ai_addr;
133 freeaddrinfo(result);
135 m_serverLength =
sizeof(m_serverAddress);
164 FD_SET(m_socketFileDescriptor, &s);
165 struct timeval timeout;
167 timeout.tv_sec = timeoutMs / 1000;
168 timeout.tv_usec = (timeoutMs % 1000) * 1000;
170 int retval = select((
int)m_socketFileDescriptor + 1, &s, NULL, NULL, timeoutMs > 0 ? &timeout : NULL);
173 std::cerr <<
"Error select!" << std::endl;
179 int length =
static_cast<int>(recvfrom(m_socketFileDescriptor, m_buf,
sizeof(m_buf), 0, (
struct sockaddr *)&m_serverAddress,
180 (socklen_t *)&m_serverLength));
182 return length < 0 ? -1 : 0;
185 msg = std::string(m_buf, length);
220 if (msg.size() > VP_MAX_UDP_PAYLOAD) {
221 std::cerr <<
"Message is too long!" << std::endl;
226 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX 227 return static_cast<int>(sendto(m_socketFileDescriptor, msg.c_str(), msg.size(), 0, (
struct sockaddr *)&m_serverAddress,
230 return sendto(m_socketFileDescriptor, msg.c_str(), (int)msg.size(), 0, (
struct sockaddr *)&m_serverAddress,
235 #elif !defined(VISP_BUILD_SHARED_LIBS) 237 void dummy_vpUDPClient(){};
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)