sys_ioctl: Simplify.
[gnulib.git] / tests / test-getsockname.c
blob9b98ff79fa81b47869763237f167514632d458e6
1 /* Test getsockname() function.
2 Copyright (C) 2011-2020 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <https://www.gnu.org/licenses/>. */
17 #include <config.h>
19 #include <sys/socket.h>
21 #include "signature.h"
22 SIGNATURE_CHECK (getsockname, int, (int, struct sockaddr *, socklen_t *));
24 #include <stdio.h>
25 #include <string.h>
26 #include <netinet/in.h>
27 #include <arpa/inet.h>
28 #include <unistd.h>
29 #include <errno.h>
31 #include "sockets.h"
32 #include "macros.h"
34 static int
35 open_server_socket (void)
37 int s, x;
38 struct sockaddr_in ia;
40 s = socket (AF_INET, SOCK_STREAM, 0);
42 x = 1;
43 setsockopt (s, SOL_SOCKET, SO_REUSEPORT, &x, sizeof (x));
45 memset (&ia, 0, sizeof (ia));
46 ia.sin_family = AF_INET;
47 inet_pton (AF_INET, "0.0.0.0", &ia.sin_addr);
48 /* Port 0 means that the system should assign a port. */
49 ia.sin_port = htons (0);
50 if (bind (s, (struct sockaddr *) &ia, sizeof (ia)) < 0)
52 perror ("bind");
53 exit (77);
56 if (listen (s, 1) < 0)
58 perror ("listen");
59 exit (77);
62 return s;
65 int
66 main (void)
68 (void) gl_sockets_startup (SOCKETS_1_1);
70 /* Test behaviour for invalid file descriptors. */
72 struct sockaddr_in addr;
73 socklen_t addrlen = sizeof (addr);
75 errno = 0;
76 ASSERT (getsockname (-1, (struct sockaddr *) &addr, &addrlen) == -1);
77 ASSERT (errno == EBADF);
80 struct sockaddr_in addr;
81 socklen_t addrlen = sizeof (addr);
83 close (99);
84 errno = 0;
85 ASSERT (getsockname (99, (struct sockaddr *) &addr, &addrlen) == -1);
86 ASSERT (errno == EBADF);
89 /* Test behaviour for a server socket. */
91 int s = open_server_socket ();
92 struct sockaddr_in addr;
93 socklen_t addrlen = sizeof (addr);
95 memset (&addr, 0, sizeof (addr));
96 ASSERT (getsockname (s, (struct sockaddr *) &addr, &addrlen) == 0);
97 ASSERT (addr.sin_family == AF_INET);
98 ASSERT (ntohs (addr.sin_port) != 0);
101 return 0;