Skip to content
UDP_Protocol.cpp 1.36 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;
}