Newer
Older
#include <string.h>
#include <arpa/inet.h>
#include <UDP_Protocol.h>
using namespace inaf::oasbo::ConnectionProtocols;
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
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 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()];
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;
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));