Blame view

check_tftp/udp.cpp 1.11 KB
Imanol-Mikel Barba Sabariego authored
1
2
3
4
5
6
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
#include "udp.h"

void setupSocket(uint16_t port, char *hostname, struct hostent *host, int timeout, struct sockaddr_in *si, int *s)
{
        if((*s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
        {
                cout << "Couldn't create socket" << endl;
                exit(3);
        }
	struct timeval tv;
	tv.tv_sec = timeout;
	tv.tv_usec = 0;
	if(setsockopt(*s, SOL_SOCKET, SO_RCVTIMEO,&tv,sizeof(tv)) < 0) 
	{
		cout << "Error setting socket timeout" << endl;
		exit(3);
	}
	if(!(host = gethostbyname(hostname)))
	{
		cout << "Client could not get host address information" << endl;
		exit(3);
	}

        memset((char *) si, 0, sizeof(*si));
        si->sin_family = AF_INET;
	memcpy (&(si->sin_addr), host->h_addr, host->h_length);
        si->sin_port = htons(port);
}

int sendMsg(int s, char *msg, size_t msgLength, struct sockaddr_in *si)
{
	return sendto(s, msg, msgLength, 0,(struct sockaddr*) si, sizeof(*si));
}

int recvMsg(int s, char *msg, size_t msgLength, struct sockaddr_in *si)
{
        size_t slen = sizeof(*si);
	return recvfrom(s, msg, msgLength, 0, (struct sockaddr *) si, (socklen_t*)&slen);
}