[UDP-to-HTTP] Use getaddrinfo() to open TCP socket
This commit is contained in:
parent
75e04cfc17
commit
050026d61f
|
@ -27,6 +27,7 @@
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
#include <strings.h>
|
#include <strings.h>
|
||||||
#include <string.h>
|
#include <string.h>
|
||||||
|
#include <netdb.h>
|
||||||
|
|
||||||
#include <assert.h>
|
#include <assert.h>
|
||||||
|
|
||||||
|
@ -297,25 +298,48 @@ void store_result(owl_result *new_result)
|
||||||
*/
|
*/
|
||||||
int init_tcp_socket()
|
int init_tcp_socket()
|
||||||
{
|
{
|
||||||
struct sockaddr_in server_addr ;
|
char http_port_str[6] ;
|
||||||
|
struct addrinfo
|
||||||
|
gai_hints,
|
||||||
|
*gai_results = NULL,
|
||||||
|
*gai_res = NULL ;
|
||||||
|
int gai_ret ; // Return value of getaddrinfo()
|
||||||
|
|
||||||
tcp_sockfd = socket(AF_INET, SOCK_STREAM, 0) ;
|
/* Get the server information */
|
||||||
if (tcp_sockfd < 0)
|
sprintf(http_port_str, "%"PRIuFAST16, options.http_port) ;
|
||||||
|
memset(&gai_hints, 0, sizeof(struct addrinfo)) ;
|
||||||
|
gai_hints.ai_family = AF_UNSPEC ; // IPv4 or IPv6
|
||||||
|
gai_hints.ai_socktype = SOCK_STREAM ;
|
||||||
|
gai_hints.ai_flags = AI_PASSIVE ;
|
||||||
|
gai_ret = getaddrinfo(NULL, http_port_str, &gai_hints, &gai_results) ;
|
||||||
|
if (gai_ret)
|
||||||
{
|
{
|
||||||
perror("Error opening the TCP socket") ;
|
fprintf(stderr, "TCP socket creation failed: getaddrinfo(): %s\n",
|
||||||
|
gai_strerror(gai_ret)) ;
|
||||||
return OWL_ERR_SOCKET_CREATE ;
|
return OWL_ERR_SOCKET_CREATE ;
|
||||||
}
|
}
|
||||||
|
|
||||||
memset(&server_addr, 0, sizeof(server_addr)) ;
|
/* Create the TCP socket:
|
||||||
server_addr.sin_family = AF_INET ;
|
* loop until both socket() and bind() succeed */
|
||||||
server_addr.sin_addr.s_addr = INADDR_ANY ;
|
for (gai_res = gai_results ; gai_res != NULL ;
|
||||||
server_addr.sin_port = htons(options.http_port) ;
|
gai_res = gai_res->ai_next)
|
||||||
|
|
||||||
|
|
||||||
if (bind(tcp_sockfd, (struct sockaddr *) &server_addr,
|
|
||||||
sizeof(server_addr)) < 0)
|
|
||||||
{
|
{
|
||||||
perror("Error binding the TCP socket") ;
|
tcp_sockfd = socket(gai_res->ai_family, gai_res->ai_socktype,
|
||||||
|
gai_res->ai_protocol) ;
|
||||||
|
if (tcp_sockfd == -1)
|
||||||
|
continue ;
|
||||||
|
|
||||||
|
if (! bind(tcp_sockfd, gai_res->ai_addr, gai_res->ai_addrlen))
|
||||||
|
break ; // Success!
|
||||||
|
|
||||||
|
close(tcp_sockfd) ;
|
||||||
|
tcp_sockfd = -1 ;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (gai_res == NULL)
|
||||||
|
{
|
||||||
|
fprintf(stderr,
|
||||||
|
"TCP socket creation failed: socket() or bind().\n") ;
|
||||||
return OWL_ERR_SOCKET_CREATE ;
|
return OWL_ERR_SOCKET_CREATE ;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue