2020-02-23 00:13:27 +00:00
# include <stdio.h>
# include <string.h>
# include <stdlib.h>
# include <netdb.h>
# include <sys/socket.h>
# include <logger.h>
2020-04-13 22:50:55 +00:00
# include <helpers.h>
2020-02-23 00:13:27 +00:00
int
2020-04-13 22:50:55 +00:00
helper_connect_tcp_server ( char * host , uint16_t port )
2020-02-23 00:13:27 +00:00
{
2020-04-13 22:50:55 +00:00
char port_str [ 6 ] ;
sprintf ( port_str , " %d " , port ) ;
2020-02-23 00:13:27 +00:00
2020-04-13 22:50:55 +00:00
int s , status ;
struct addrinfo hints , * res ;
memset ( & hints , 0 , sizeof hints ) ;
hints . ai_family = AF_INET ; //set IP Protocol flag (IPv4 or IPv6 - we don't care)
hints . ai_socktype = SOCK_STREAM ; //set socket flag
2020-02-23 00:13:27 +00:00
2020-04-13 22:50:55 +00:00
if ( ( status = getaddrinfo ( host , port_str , & hints , & res ) ) ! = 0 ) { //getaddrinfo() will evaluate the given address, using the hints-flags and port, and return an IP address and other server infos
LOG_ERROR ( " getaddrinfo: %s \n " , gai_strerror ( status ) ) ;
return - 1 ;
}
2020-02-23 00:13:27 +00:00
2020-04-13 22:50:55 +00:00
//res got filled out by getaddrinfo() for us
s = socket ( res - > ai_family , res - > ai_socktype , res - > ai_protocol ) ; //creating Socket
2020-02-23 00:13:27 +00:00
2020-04-13 22:50:55 +00:00
if ( ( status = connect ( s , res - > ai_addr , res - > ai_addrlen ) ) ! = 0 ) {
LOG_ERROR ( " connect() failed " ) ;
freeaddrinfo ( res ) ;
return - 1 ;
}
2020-02-23 00:13:27 +00:00
2020-04-13 22:50:55 +00:00
freeaddrinfo ( res ) ;
2020-02-23 00:13:27 +00:00
2020-04-13 22:50:55 +00:00
return s ;
}