Skip to content
TCP_Protocol.cpp 2.46 KiB
Newer Older
Valerio Pastore's avatar
Valerio Pastore committed
#include <sys/socket.h>
#include <arpa/inet.h>
#include <fstream>
#include <map>
#include <TCP_Protocol.h>


TCPProtocol::TCPProtocol(std::string hs, int prt){
	this->host = hs;
	this->port = prt;
	fd_sock = 0;
}


/*
 * Implementation of the BaseSocket connect for the TCP protocol
 *
 * @return file_descriptor [-1 error]
 */
int TCPProtocol::connectToClient() {
	int sockfd, newSocket;
	struct sockaddr_in servaddr;
	int addrlen = sizeof(servaddr);
	// Creating socket file descriptor
	if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == 0){
		perror("socket failed");
		return -1;
	}
	servaddr.sin_family = AF_INET;
	servaddr.sin_addr.s_addr = INADDR_ANY;
	servaddr.sin_port = htons( port );
	if (bind(sockfd, (struct sockaddr *)&servaddr,sizeof(servaddr))<0){
		perror("bind failed");
		return -1;
	}

	std::cout << "Waiting for connection" << std::endl;

	if (listen(sockfd, 1) < 0){
		perror("listen error");
		return -1;
	}
	if ((newSocket = accept(sockfd, (struct sockaddr *)&servaddr,(socklen_t*)&addrlen))<0){
		perror("accept error");
		return -1;
	}
	std::cout << "Connected" << std::endl;

	this->fd_sock = newSocket;
	return newSocket;

}

int TCPProtocol::connectToServer(){
	int sock = 0;
	struct sockaddr_in cli_addr;
	if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){
		printf("\n Socket creation error \n");
		return -1;
	}

	cli_addr.sin_family = AF_INET;
	cli_addr.sin_port = htons(port);

	// Convert IPv4 and IPv6 addresses from text to binary form
	if(inet_pton(AF_INET, host.c_str(), &cli_addr.sin_addr)<=0){
		printf("\nInvalid address/ Address not supported \n");
		return -1;
	}

	if (connect(sock, (struct sockaddr *)&cli_addr, sizeof(cli_addr)) < 0){
		printf("\nConnection Failed \n");
		return -1;
	}
	std::cout << "Connected" << std::endl;
	this->fd_sock = sock;
	return sock;
}

/*
 * Implementation of the BaseSocket readPacket for the TCP 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]
 */
int TCPProtocol::rcvPacketFromCli(BasePacket &pack){
	int rec = recv(this->fd_sock, &pack.getBufferPtr()[0], pack.getHeaderSize(), MSG_WAITALL);
	if(rec > 0){
		pack.computeHeaderFieldValues();
		rec+= recv(this->fd_sock, &pack.getBufferPtr()[rec], pack.getPayloadSize() + pack.getTailSize(), MSG_WAITALL);
	}
	return rec;
}

int TCPProtocol::sendPacketToSrv(BasePacket &pack){
	int val = send(fd_sock, pack.getBufferPtr(), pack.getPacketSize(), MSG_CONFIRM);
	return val;
}