inline sockaddr_storage get_sockaddr_from(const std::string& ip, const std::string& port) { int portid = atoi(port.c_str()); unsigned long addr = inet_addr(ip.c_str()); struct addrinfo hints, *servinfo; int rv; memset(&hints, 0, sizeof hints); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_DGRAM; sockaddr_storage ret; memset(&ret, 0, sizeof(sockaddr_storage)); if ((rv = getaddrinfo(ip.c_str(), port.c_str(), &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); return sockaddr_storage(); } /*for(addrinfo* p = servinfo; p != nullptr; p = p->ai_next) { sockaddr_in* ipv4 = (sockaddr_in*)p->ai_addr; memcpy(&ret, ipv4, sizeof(sockaddr_in)); }*/ memcpy(&ret, servinfo->ai_addr, servinfo->ai_addrlen); freeaddrinfo(servinfo); return ret; }
void Socket::sendAndReceive (const std::string& destination_address, void* data, size_t size, std::function<int(void*)> callback, const bool broadcast) { sockaddr_in destAddr = fillAddr(destination_address, STANDARD_GVCP_PORT); setBroadcast(broadcast); ssize_t send = sendto(fd, (uint8_t*)data, size, 0, (struct sockaddr*)&destAddr, sizeof(destAddr)); if (send <= 0) { throw SocketSendToException(); } else { // we have nothing to wait for end just end here if (callback == NULL) { return; } timeval timeout; timeout.tv_sec = timeout_ms / 1000; timeout.tv_usec = (timeout_ms % 1000) * 1000; fd_set fds; FD_ZERO(&fds); FD_SET(fd, &fds); while (select(fd+1, &fds, NULL, NULL, &timeout) > 0) { char msg[1024]; struct sockaddr_storage sender = sockaddr_storage(); socklen_t sendsize = 0; if (recvfrom(fd, msg, sizeof(msg), 0, (sockaddr*)&sender, &sendsize) >= 0) { if (callback(msg) == SendAndReceiveSignals::END) { return; } // not working due to gcc bug //auto cam = std::make_shared<Camera>(ack, interfaces.at(i).socket, interfaces.at(i).name); } } } }