1 /* Create sockets for use in tests (client side).
2 Copyright (C) 2011-2021 Free Software Foundation, Inc.
3
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.
8
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.
13
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/>. */
16
17 /* Written by Bruno Haible <bruno@clisp.org>, 2011. */
18
19 #include <stdio.h>
20 #include <sys/socket.h>
21 #include <netinet/in.h>
22 #include <arpa/inet.h>
23
24 /* Creates a client socket, by connecting to a server on the given port. */
25 static int
26 create_client_socket (int port)
/* ![[previous]](../icons/n_left.png)
![[next]](../icons/n_right.png)
![[first]](../icons/n_first.png)
![[last]](../icons/n_last.png)
![[top]](../icons/top.png)
![[bottom]](../icons/bottom.png)
![[index]](../icons/index.png)
*/
27 {
28 int client_socket;
29
30 /* Create a client socket. */
31 client_socket = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP);
32 ASSERT (client_socket >= 0);
33 /* Connect to the server process at the specified port. */
34 {
35 struct sockaddr_in addr;
36
37 memset (&addr, 0, sizeof (addr)); /* needed on AIX and OSF/1 */
38 addr.sin_family = AF_INET;
39 #if 0 /* Unoptimized */
40 inet_pton (AF_INET, "127.0.0.1", &addr.sin_addr);
41 #elif 0 /* Nearly optimized */
42 addr.sin_addr.s_addr = htonl (0x7F000001); /* 127.0.0.1 */
43 #else /* Fully optimized */
44 {
45 unsigned char dotted[4] = { 127, 0, 0, 1 }; /* 127.0.0.1 */
46 memcpy (&addr.sin_addr.s_addr, dotted, 4);
47 }
48 #endif
49 addr.sin_port = htons (port);
50
51 ASSERT (connect (client_socket,
52 (const struct sockaddr *) &addr, sizeof (addr))
53 == 0);
54 }
55
56 return client_socket;
57 }