#include #include #include using namespace inaf::oasbo::ConnectionProtocols; UDPProtocol::UDPProtocol(std::string hs, int prt){ this->host = hs; this->port = prt; fd_sock = 0; memset(&cliaddr, 0, sizeof(cliaddr)); memset(&srvaddr, 0, sizeof(srvaddr)); // Filling server information srvaddr.sin_family = AF_INET; // IPv4 srvaddr.sin_addr.s_addr = inet_addr(host.c_str()); srvaddr.sin_port = htons(port); } /* * Implementation of the BaseSocket connect for the UDP protocol * */ int UDPProtocol::connectToClient() { int sockfd; // Creating socket file descriptor if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) { perror("socket creation failed"); return -1; } // Set timeout to the socket struct timeval tv; tv.tv_sec = 10; tv.tv_usec = 0; setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv); // Bind the socket with the server address if ( bind(sockfd, (const struct sockaddr *)&srvaddr, sizeof(srvaddr)) < 0 ) { perror("bind failed"); return -1; } this->fd_sock = sockfd; return sockfd; } int UDPProtocol::connectToServer(){ int sockfd = 0; // Creating socket file descriptor if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) { perror("socket creation failed"); exit(EXIT_FAILURE); } printf("Connection made\n"); this->fd_sock = sockfd; return sockfd; } /* * Implementation of the BaseSocket readPacket for the UDP protocol * * @param pack: address of the packet object * @param buff: buffer to write the read bytes * * @return number of bytes received [-1 error, 0 done] */ template typename Container> int UDPProtocol::rcvPacketFromCli(PacketLib::BasePacket &pack){ size_t headerSize = pack.getHeaderSize(); uint8_t *buff = new uint8_t[pack.getMaxPacketSize()]; socklen_t len = sizeof(cliaddr); int rec = recvfrom(fd_sock, buff, pack.getMaxPacketSize(),MSG_WAITFORONE, ( struct sockaddr *) &cliaddr,&len); if(rec > 0){ pack.copyToBinaryPointer(buff, pack.getHeaderSize(), pack.getPayloadSize() + pack.getTailSize()); } delete buff; return rec; } template typename Container> int UDPProtocol::sendPacketToSrv(PacketLib::BasePacket &pack){ int val = sendto(fd_sock, pack.getBinaryPointer(), pack.getHeaderSize()+pack.getPayloadSize()+pack.getTailSize(), MSG_CONFIRM,( struct sockaddr *) &srvaddr,sizeof(srvaddr)); return val; }