blob: 0dc5d8e5b7ad41ded95579b1cfe987101650211d [file] [log] [blame]
Jeff Thompson7790c682013-07-17 17:22:12 -07001/**
2 * @author: Jeff Thompson
3 * See COPYING for copyright and distribution information.
4 */
5
6#include "UdpTransport.h"
7
8#include <stdio.h>
9#include <stdlib.h>
10#include <unistd.h>
11#include <netdb.h>
12#include <sys/types.h>
13#include <netinet/in.h>
14#include <sys/socket.h>
15#include <arpa/inet.h>
16#include "../util/ndn_memory.h"
17
18ndn_Error ndn_UdpTransport_connect(struct ndn_UdpTransport *self, char *host, unsigned short port)
19{
20 if (self->socketDescriptor >= 0) {
21 close(self->socketDescriptor);
22 self->socketDescriptor = -1;
23 }
24
25 struct addrinfo hints;
26 ndn_memset((unsigned char *)&hints, 0, sizeof(hints));
27 hints.ai_family = AF_UNSPEC;
28 hints.ai_socktype = SOCK_DGRAM;
29
30 char portString[10];
31 sprintf(portString, "%d", port);
32
33 struct addrinfo *serverInfo;
34 if (getaddrinfo(host, portString, &hints, &serverInfo) != 0)
35 return NDN_ERROR_UdpTransport_error_in_getaddrinfo;
36
37 // loop through all the results and connect to the first we can
38 struct addrinfo *p;
39 int socketDescriptor;
40 for(p = serverInfo; p != NULL; p = p->ai_next) {
41 if ((socketDescriptor = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
42 continue;
43
44 if (connect(socketDescriptor, p->ai_addr, p->ai_addrlen) == -1) {
45 close(socketDescriptor);
46 continue;
47 }
48
49 break;
50 }
51
52 if (p == NULL) {
53 freeaddrinfo(serverInfo);
54 return NDN_ERROR_UdpTransport_cannot_connect_to_socket;
55 }
56
57 freeaddrinfo(serverInfo);
58 self->socketDescriptor = socketDescriptor;
59
60 return 0;
61}
62
63ndn_Error ndn_UdpTransport_send(struct ndn_UdpTransport *self, unsigned char *data, unsigned int dataLength)
64{
65 if (self->socketDescriptor < 0)
66 return NDN_ERROR_UdpTransport_socket_is_not_open;
67
68 int nBytes;
69 while (1) {
70 if ((nBytes = send(self->socketDescriptor, data, dataLength, 0)) < 0)
71 return NDN_ERROR_UdpTransport_error_in_send;
72 if (nBytes >= dataLength)
73 break;
74
75 // Send more.
76 dataLength -= nBytes;
77 }
78
79 return 0;
80}
81
82ndn_Error ndn_UdpTransport_receive
83(struct ndn_UdpTransport *self, unsigned char *buffer, unsigned int bufferLength, unsigned int *nBytesOut)
84{
85 if (self->socketDescriptor < 0)
86 return NDN_ERROR_UdpTransport_socket_is_not_open;
87
88 int nBytes;
89 if ((nBytes = recv(self->socketDescriptor, buffer, bufferLength, 0)) == -1)
90 return NDN_ERROR_UdpTransport_error_in_recv;
91
92 *nBytesOut = (unsigned int)nBytes;
93
94 return 0;
95}