controller-legacy/helpers/connect_server.c

38 lines
1 KiB
C
Raw Normal View History

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>
#include <helper.h>
int
helper_connect_server(char* host, char* 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, &hints, &res)) != 0) { //getaddrinfo() will evaluate the given address, using the hints-flags and port, and return an IP address and other server infos
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(status));
exit(EXIT_FAILURE);
}
//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) {
fprintf(stderr, "Keine Verbindung mit dem Netzwerk möglich.\n");
freeaddrinfo(res);
exit(EXIT_FAILURE);
}
freeaddrinfo(res);
return s;
}