40 lines
1.1 KiB
C
40 lines
1.1 KiB
C
|
#include <stdio.h>
|
||
|
#include <string.h>
|
||
|
#include <stdlib.h>
|
||
|
#include <netdb.h>
|
||
|
#include <sys/socket.h>
|
||
|
|
||
|
#include <logger.h>
|
||
|
#include <helpers.h>
|
||
|
|
||
|
int
|
||
|
helper_connect_tcp_server(char* host, uint16_t port)
|
||
|
{
|
||
|
char port_str[6];
|
||
|
sprintf(port_str, "%d", port);
|
||
|
|
||
|
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
|
||
|
|
||
|
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;
|
||
|
}
|
||
|
|
||
|
//res got filled out by getaddrinfo() for us
|
||
|
s = socket(res->ai_family, res->ai_socktype, res->ai_protocol); //creating Socket
|
||
|
|
||
|
if ((status = connect(s, res->ai_addr, res->ai_addrlen)) != 0) {
|
||
|
LOG_ERROR("connect() failed\n");
|
||
|
freeaddrinfo(res);
|
||
|
return -1;
|
||
|
}
|
||
|
|
||
|
freeaddrinfo(res);
|
||
|
|
||
|
return s;
|
||
|
}
|