#include #include #include #include #include using namespace inaf::oasbo::ConnectionProtocols; 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(PacketLib::BasePacket &pack){ size_t headerSize = pack.getHeaderSize(); uint8_t *buff = new uint8_t[pack.getMaxPacketSize()]; size_t rec = recv(this->fd_sock, &buff[0], headerSize, MSG_WAITALL); pack.copyToBinaryPointer(buff, headerSize); if(rec == headerSize){ rec+= recv(this->fd_sock, &buff[headerSize], pack.getPayloadSize() + pack.getTailSize(), MSG_WAITALL); pack.copyToBinaryPointer(&buff[headerSize], pack.getPayloadSize() + pack.getTailSize(), headerSize); } delete buff; return rec; } int TCPProtocol::sendPacketToSrv(PacketLib::BasePacket &pack){ int val = send(fd_sock, pack.getBinaryPointer(), pack.getHeaderSize()+pack.getPayloadSize()+pack.getTailSize(), MSG_CONFIRM); return val; }