-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgetsockfd.c
54 lines (47 loc) · 1.36 KB
/
getsockfd.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
54
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#ifdef __cplusplus
extern "C" {
#endif
int getsockfd(const char * host, const char * port)
{
struct hostent * hostent;
struct servent * servent;
struct sockaddr_in address;
int numero, sock;
memset(&address, 0, sizeof(struct sockaddr_in));
if (inet_aton(host, &(address.sin_addr)) == 0) {
if ((hostent = gethostbyname(host)) == NULL) {
fprintf(stderr, "%s: unknow host\n", __FUNCTION__);
return -1;
}
address.sin_addr.s_addr = ((struct in_addr *) (hostent->h_addr))->s_addr;
}
if (sscanf(port, "%d", &numero) == 1) {
address.sin_port = htons(numero);
} else if ((servent = getservbyname(port, "tcp")) == NULL) {
fprintf(stderr, "%s: unknow service %s\n", __FUNCTION__, port);
return -1;
} else {
address.sin_port = servent->s_port;
}
address.sin_family = AF_INET;
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("socket");
return -1;
}
if (connect(sock, (struct sockaddr *) &address, sizeof(struct sockaddr_in)) < 0) {
perror("connect");
return -1;
}
return sock;
}
#ifdef __cplusplus
}
#endif