forked from PL4typus/virt_cacard
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconnection.c
53 lines (44 loc) · 1.17 KB
/
connection.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include "connection.h"
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdint.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
SOCKET connectsock(const char *hostname, uint16_t port)
{
struct addrinfo hints, *res = NULL, *cur;
SOCKET sock = INVALID_SOCKET;
char _port[10];
int err=0;
if (snprintf(_port, sizeof _port, "%hu", port) < 0)
goto err;
_port[(sizeof _port) -1] = '\0';
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_NUMERICSERV;
if (getaddrinfo(hostname, _port, &hints, &res) != 0)
goto err;
for (cur = res; cur; cur = cur->ai_next) {
sock = socket(cur->ai_family, cur->ai_socktype, cur->ai_protocol);
if (sock == INVALID_SOCKET)
continue;
err = connect(sock, cur->ai_addr, cur->ai_addrlen);
if (err == -1){
perror("connection problem");
goto err;
}
else break;
close(sock);
}
err:
freeaddrinfo(res);
return sock;
}
/* vim: set ts=4 sw=4 tw=0 noet expandtab: */