-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsock.c
62 lines (46 loc) · 1.37 KB
/
sock.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
55
56
57
58
59
60
61
62
#include "sock.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <sys/socket.h> // socket(), bind()
#include <arpa/inet.h> // htons()
#include <netdb.h> // struct hostent
int sock_conn(const char *host, const int port)
{
struct sockaddr_in client;
struct hostent *he;
int socket_desc;
// Cria o socket
socket_desc = socket(AF_INET, SOCK_STREAM, 0);
if (socket_desc == -1) return -1;
// Pega o IP
if ( (he = gethostbyname(host)) == NULL) return -1;
else memcpy(&client.sin_addr, he->h_addr, he->h_length);
client.sin_family = AF_INET;
client.sin_port = htons(port);
if (connect(socket_desc, (struct sockaddr *)&client, sizeof(client)) < 0)
{
puts("Connect error!");
}
return socket_desc;
}
int sock_bind(int port, int n_connections)
{
int socket_desc;
struct sockaddr_in server;
socket_desc = socket(AF_INET, SOCK_STREAM, 0);
if (socket_desc == -1) return -1;
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(port);
if (bind(socket_desc, (const struct sockaddr *)&server, sizeof(server)) < 0) return -2;
listen(socket_desc, n_connections);
return socket_desc;
}
int sock_accept(int sock_desc)
{
struct sockaddr_in client;
int c = sizeof(struct sockaddr_in);
int new_socket = accept(sock_desc, (struct sockaddr *)&client, (socklen_t *)&c);
return new_socket;
}