@@ -88,35 +88,53 @@ static void add_peers(WorkerConfig *cfg)
8888/* Returns the created socket, or -1 if failed. */
8989static int create_listening_socket (const char * host , int port ) {
9090 int optval ;
91- struct sockaddr_in addr ;
92- int s = socket (AF_INET , SOCK_STREAM , 0 );
93- if (s == -1 ) {
94- fprintf (stderr , "cannot create the listening socket: %s\n" , strerror (errno ));
91+ struct addrinfo * addrs = NULL ;
92+ struct addrinfo hint ;
93+ struct addrinfo * a ;
94+ char portstr [6 ];
95+ int rc ;
96+
97+ memset (& hint , 0 , sizeof (hint ));
98+ hint .ai_socktype = SOCK_STREAM ;
99+ hint .ai_family = AF_INET ;
100+ snprintf (portstr , 6 , "%d" , port );
101+ hint .ai_protocol = getprotobyname ("tcp" )-> p_proto ;
102+
103+ if ((rc = getaddrinfo (host , portstr , & hint , & addrs )))
104+ {
105+ elog (WARNING , "failed to resolve address '%s:%d': %s" ,
106+ host , port , gai_strerror (rc ));
95107 return -1 ;
96108 }
97109
98- optval = 1 ;
99- setsockopt (s , IPPROTO_TCP , TCP_NODELAY , (char const * )& optval , sizeof (optval ));
100- setsockopt (s , SOL_SOCKET , SO_REUSEADDR , (char const * )& optval , sizeof (optval ));
110+ for (a = addrs ; a != NULL ; a = a -> ai_next )
111+ {
112+ int s = socket (AF_INET , SOCK_STREAM , 0 );
113+ if (s == -1 ) {
114+ elog (WARNING , "cannot create the listening socket: %s" , strerror (errno ));
115+ continue ;
116+ }
101117
102- addr .sin_family = AF_INET ;
103- if (inet_aton (host , & addr .sin_addr ) == 0 ) {
104- fprintf (stderr , "cannot convert the host string '%s' to a valid address\n" , host );
105- return -1 ;
106- }
107- addr .sin_port = htons (port );
108- fprintf (stderr , "binding tcp %s:%d\n" , host , port );
109- if (bind (s , (struct sockaddr * )& addr , sizeof (addr )) == -1 ) {
110- fprintf (stderr , "cannot bind the listening socket: %s\n" , strerror (errno ));
111- return -1 ;
112- }
118+ optval = 1 ;
119+ setsockopt (s , IPPROTO_TCP , TCP_NODELAY , (char const * )& optval , sizeof (optval ));
120+ setsockopt (s , SOL_SOCKET , SO_REUSEADDR , (char const * )& optval , sizeof (optval ));
121+
122+ fprintf (stderr , "binding tcp %s:%d\n" , host , port );
123+ if (bind (s , a -> ai_addr , a -> ai_addrlen ) < 0 ) {
124+ elog (WARNING , "cannot bind the listening socket: %s" , strerror (errno ));
125+ close (s );
126+ continue ;
127+ }
113128
114- if (listen (s , LISTEN_QUEUE_SIZE ) == -1 ) {
115- fprintf (stderr , "failed to listen the socket: %s\n" , strerror (errno ));
116- return -1 ;
129+ if (listen (s , LISTEN_QUEUE_SIZE ) == -1 ) {
130+ elog (WARNING , "failed to listen the socket: %s" , strerror (errno ));
131+ close (s );
132+ continue ;
133+ }
134+ return s ;
117135 }
118-
119- return s ;
136+ elog ( WARNING , "failed to find proper protocol" );
137+ return -1 ;
120138}
121139
122140static bool add_socket (int sock )
0 commit comments