-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzcu_import.c
More file actions
117 lines (95 loc) · 2.51 KB
/
zcu_import.c
File metadata and controls
117 lines (95 loc) · 2.51 KB
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
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <unistd.h>
#include "zcu_xport.h"
/*
* POSIX-compliant C code to resolve a hostname or IPv4 address string
* into a struct in_addr (IPv4 address).
*
* Works with both dotted-quad IP strings and DNS hostnames.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <netdb.h>
#include <arpa/inet.h>
static int zsock = -1;
static struct in_addr zaddr;
/*
* resolve_address:
* Takes a string (hostname or IPv4 address)
* On success: returns 0 and fills *addr with the IPv4 address
* On failure: returns -1
*/
static int resolve_address(const char *host, struct in_addr *addr) {
struct addrinfo hints, *res = NULL;
int ret;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET; // Only IPv4
hints.ai_socktype = SOCK_STREAM; // Any type works, but stream is standard
ret = getaddrinfo(host, NULL, &hints, &res);
if (ret != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(ret));
return -1;
}
if (res == NULL) {
fprintf(stderr, "No addresses found for %s\n", host);
return -1;
}
// Extract IPv4 address
struct sockaddr_in *ipv4 = (struct sockaddr_in *)res->ai_addr;
*addr = ipv4->sin_addr;
freeaddrinfo(res);
return 0;
}
// set the peer hostname that will receive the samples
int zcu_xport_set_dest(const char *host)
{
return resolve_address(host, &zaddr);
}
int zcu_xport_send(int16_t *samples, size_t nsamples)
{
if (nsamples != 4096)
return -1;
if (zsock == -1) {
int zsock = socket(AF_INET, SOCK_STREAM, 0);
if (zsock < 0)
return -1;
struct sockaddr_in addr = { .sin_family = AF_INET };
addr.sin_port = htons(XPORT_PORT);
addr.sin_addr = zaddr;
if (connect(zsock, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
int err = errno;
close(zsock);
errno = err;
return -1;
}
}
size_t sent = 0;
size_t samplesz = sizeof(int16_t) * nsamples;
const unsigned char *p = (unsigned char *) samples;
while (sent < samplesz) {
size_t len = samplesz - sent;
ssize_t bytes = write(zsock, p + sent, len);
if (bytes < 0) {
close(zsock);
zsock = -1;
return -1;
}
sent += bytes;
}
return 0;
}
#ifdef __TEST__
#include <assert.h>
int main(int argc, char **argv)
{
int16_t samples[4096];
assert(argc >= 2);
assert(zcu_xport_set_dest(argv[1]) == 0);
assert(zcu_xport_send(samples, 4096) == 0);
}
#endif