-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.c
72 lines (54 loc) · 1.81 KB
/
server.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
63
64
65
66
67
68
69
70
71
72
#include <netinet/in.h>
#include <stdio.h>
#include <string.h> /* strlen */
#include <sys/socket.h>
#include <arpa/inet.h> /* inet_addr */
#include <unistd.h> /* close */
int main(int argc, char *argv[])
{
int socket_desc, c, new_socket;
struct sockaddr_in server, client;
char *message, client_reply[2000];
socket_desc = socket(AF_INET, SOCK_STREAM, 0);
if (socket_desc == -1)
{
printf("Não foi possível criar o socket\n");
return 1;
}
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(8888);
if (bind(socket_desc, (struct sockaddr *) &server, sizeof(server)) < 0)
{
printf("Erro ao fazer o bind\n");
return 1;
}
printf("Bind efetuado.\n");
listen(socket_desc, 3);
printf("Aguardando conexões...\n");
c = sizeof(struct sockaddr_in);
while ((new_socket = accept(socket_desc, (struct sockaddr *) &client, (socklen_t*) &c)))
{
char *client_ip = inet_ntoa(client.sin_addr);
int client_port = ntohs(client.sin_port);
printf("conexão aceita do client %s:%d\n", client_ip, client_port);
do {
bzero(client_reply, sizeof(client_reply));
if (recv(new_socket, client_reply, 2000, 0) < 0)
{
printf("Falha no recv\n");
return 1;
}
printf("Resposta recebida.\n");
printf("%s\n", client_reply);
message = "Olá Cliente! Recebi sua conexão, mas preciso ir agora! Tchau!";
write(new_socket, message, strlen(message));
} while(strcmp(client_reply, "exit") != 0);
}
if (new_socket < 0)
{
printf("Erro ao aceitar conexão\n");
return 1;
}
return 0;
}