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
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;
}