summaryrefslogtreecommitdiff
path: root/socket.c
blob: 6e1db07c3fc93242ad084dcc7ddcd732c890d1e7 (plain) (blame)
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
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/time.h>

#define TEST2(c, l, ...) ((c) ? 1 : \
(err++,printf(__FILE__":"#l": "#c" failed: " __VA_ARGS__),putchar('\n'),0))
#define TEST1(c, l, ...) TEST2(c, l, __VA_ARGS__)
#define TEST(c, ...) TEST1(c, __LINE__, __VA_ARGS__)

#define TESTE(c) TEST(c, "errno = %s", strerror(errno))

int test_socket(void)
{
	int err = 0;
	struct sockaddr_in sa = { .sin_family = AF_INET };
	int s, c;
	char buf[100];

	TESTE((s=socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP))>=0);
	TESTE(bind(s, (void *)&sa, sizeof sa)==0);
	TESTE(getsockname(s, (void *)&sa, (socklen_t[]){sizeof sa})==0);

	TESTE(setsockopt(s, SOL_SOCKET, SO_RCVTIMEO,
		&(struct timeval){.tv_usec=1}, sizeof(struct timeval))==0);

	TESTE((c=socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP))>=0);
	sa.sin_addr.s_addr = htonl(0x7f000001);
	TESTE(sendto(c, "x", 1, 0, (void *)&sa, sizeof sa)==1);
	TESTE(recvfrom(s, buf, sizeof buf, 0, (void *)&sa, (socklen_t[]){sizeof sa})==1);
	TEST(buf[0]=='x', "'%c'", buf[0]);

	close(c);
	close(s);
	
	return err;
}