xref: /linux/tools/testing/selftests/net/bind_timewait.c (revision c532de5a67a70f8533d495f8f2aaa9a0491c3ad0)
1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright Amazon.com Inc. or its affiliates. */
3 
4 #include <sys/socket.h>
5 #include <netinet/in.h>
6 
7 #include "../kselftest_harness.h"
8 
9 FIXTURE(bind_timewait)
10 {
11 	struct sockaddr_in addr;
12 	socklen_t addrlen;
13 };
14 
15 FIXTURE_VARIANT(bind_timewait)
16 {
17 	__u32 addr_const;
18 };
19 
20 FIXTURE_VARIANT_ADD(bind_timewait, localhost)
21 {
22 	.addr_const = INADDR_LOOPBACK
23 };
24 
25 FIXTURE_VARIANT_ADD(bind_timewait, addrany)
26 {
27 	.addr_const = INADDR_ANY
28 };
29 
30 FIXTURE_SETUP(bind_timewait)
31 {
32 	self->addr.sin_family = AF_INET;
33 	self->addr.sin_port = 0;
34 	self->addr.sin_addr.s_addr = htonl(variant->addr_const);
35 	self->addrlen = sizeof(self->addr);
36 }
37 
38 FIXTURE_TEARDOWN(bind_timewait)
39 {
40 }
41 
42 void create_timewait_socket(struct __test_metadata *_metadata,
43 			    FIXTURE_DATA(bind_timewait) *self)
44 {
45 	int server_fd, client_fd, child_fd, ret;
46 	struct sockaddr_in addr;
47 	socklen_t addrlen;
48 
49 	server_fd = socket(AF_INET, SOCK_STREAM, 0);
50 	ASSERT_GT(server_fd, 0);
51 
52 	ret = bind(server_fd, (struct sockaddr *)&self->addr, self->addrlen);
53 	ASSERT_EQ(ret, 0);
54 
55 	ret = listen(server_fd, 1);
56 	ASSERT_EQ(ret, 0);
57 
58 	ret = getsockname(server_fd, (struct sockaddr *)&self->addr, &self->addrlen);
59 	ASSERT_EQ(ret, 0);
60 
61 	client_fd = socket(AF_INET, SOCK_STREAM, 0);
62 	ASSERT_GT(client_fd, 0);
63 
64 	ret = connect(client_fd, (struct sockaddr *)&self->addr, self->addrlen);
65 	ASSERT_EQ(ret, 0);
66 
67 	addrlen = sizeof(addr);
68 	child_fd = accept(server_fd, (struct sockaddr *)&addr, &addrlen);
69 	ASSERT_GT(child_fd, 0);
70 
71 	close(child_fd);
72 	close(client_fd);
73 	close(server_fd);
74 }
75 
76 TEST_F(bind_timewait, 1)
77 {
78 	int fd, ret;
79 
80 	create_timewait_socket(_metadata, self);
81 
82 	fd = socket(AF_INET, SOCK_STREAM, 0);
83 	ASSERT_GT(fd, 0);
84 
85 	ret = bind(fd, (struct sockaddr *)&self->addr, self->addrlen);
86 	ASSERT_EQ(ret, -1);
87 	ASSERT_EQ(errno, EADDRINUSE);
88 
89 	close(fd);
90 }
91 
92 TEST_HARNESS_MAIN
93