Skip to content
UDP_Protocol.cpp 2.43 KiB
Newer Older
Valerio Pastore's avatar
Valerio Pastore committed
#include <string.h>
#include <arpa/inet.h>

#include <UDP_Protocol.h>

Valerio Pastore's avatar
Valerio Pastore committed
using namespace inaf::oasbo::ConnectionProtocols;
Valerio Pastore's avatar
Valerio Pastore committed

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]
 */
Valerio Pastore's avatar
Valerio Pastore committed
template<typename Value, template<typename> typename Container>
int UDPProtocol::rcvPacketFromCli(PacketLib::BasePacket<Container,Value> &pack){
	size_t headerSize = pack.getHeaderSize();
	uint8_t *buff = new uint8_t[pack.getMaxPacketSize()];
Valerio Pastore's avatar
Valerio Pastore committed
	socklen_t len = sizeof(cliaddr);
Valerio Pastore's avatar
Valerio Pastore committed
	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;
Valerio Pastore's avatar
Valerio Pastore committed
	return rec;
}


Valerio Pastore's avatar
Valerio Pastore committed
template<typename Value, template<typename> typename Container>
int UDPProtocol::sendPacketToSrv(PacketLib::BasePacket<Container,Value> &pack){
	int val = sendto(fd_sock, pack.getBinaryPointer(), pack.getHeaderSize()+pack.getPayloadSize()+pack.getTailSize(), MSG_CONFIRM,( struct sockaddr *) &srvaddr,sizeof(srvaddr));
Valerio Pastore's avatar
Valerio Pastore committed
	return val;
}