File: config.reuseaddr.c

package info (click to toggle)
gnustep-base 1.26.0-4
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 27,260 kB
  • sloc: objc: 204,878; ansic: 32,160; sh: 157; makefile: 128; cpp: 122; xml: 32
file content (106 lines) | stat: -rw-r--r-- 2,332 bytes parent folder | download | duplicates (5)
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
/*
  Copyright (C) 2005 Free Software Foundation

  Copying and distribution of this file, with or without modification,
  are permitted in any medium without royalty provided the copyright
  notice and this notice are preserved.
*/
#if defined(__MINGW32__) || defined(__MINGW64__)
#include <windows.h>
#include <winsock2.h>
#else
#include <time.h>
#include <sys/time.h>
#include <sys/param.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
#endif /* __MINGW__ */

#include <sys/file.h>
#include <sys/stat.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>

#ifndef	INADDR_NONE
#define	INADDR_NONE	-1
#endif

// Maximum data in single I/O operation
#define	NETBUF_SIZE	4096

main()
{
  struct sockaddr_in	sin;
  int	size = sizeof(sin);
  int	status = 1;
  int	port;
  int	net;

  memset(&sin, '\0', sizeof(sin));
  sin.sin_family = AF_INET;
  sin.sin_addr.s_addr = htonl(INADDR_ANY);
  sin.sin_port = 0;

  if ((net = socket(AF_INET, SOCK_STREAM, PF_UNSPEC)) < 0)
    {
      fprintf(stderr, "unable to create socket 1\n");
      return 2;
    }

  if (setsockopt(net, SOL_SOCKET, SO_REUSEADDR,
    (char *)&status, sizeof(status)) < 0)
    {
      fprintf(stderr, "unable to set socket 1 option\n");
      (void) close(net);
      return 1;
    }

  if (bind(net, (struct sockaddr *)&sin, sizeof(sin)) < 0)
    {
      fprintf(stderr, "unable to bind socket 1\n");
      (void) close(net);
      return 2;
    }

  listen(net, 5);

  if (getsockname(net, (struct sockaddr*)&sin, &size) < 0)
    {
      fprintf(stderr, "unable to get socket 1 name\n");
      (void) close(net);
      return 2;
    }

  port = sin.sin_port;
  memset(&sin, '\0', sizeof(sin));
  sin.sin_family = AF_INET;
  sin.sin_addr.s_addr = htonl(INADDR_ANY);
  sin.sin_port = port;

  if ((net = socket(AF_INET, SOCK_STREAM, PF_UNSPEC)) < 0)
    {
      fprintf(stderr, "unable to create socket 2\n");
      return 2;
    }

  if (setsockopt(net, SOL_SOCKET, SO_REUSEADDR,
    (char *)&status, sizeof(status)) < 0)
    {
      fprintf(stderr, "unable to set socket 2 option\n");
      (void) close(net);
      return 1;
    }

  /*
   * Now ... this bind should fail unless SO_REUSEADDR is broken.
   */
  if (bind(net, (struct sockaddr *)&sin, sizeof(sin)) < 0)
    {
      return 0;
    }
  return 1;
}