-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.c
More file actions
83 lines (69 loc) · 2.02 KB
/
client.c
File metadata and controls
83 lines (69 loc) · 2.02 KB
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
73
74
75
76
77
78
79
80
81
82
83
#include <sys/socket.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 9999
#define BUFFER_SIZE 1024
int main()
{
int client_socket = socket(AF_INET, SOCK_STREAM, 0);
if (client_socket < 0)
{
printf("[!] Error when creating a socket!\n");
exit(EXIT_FAILURE);
}
printf("[+] Socket is created\n");
struct sockaddr_in server_address;
server_address.sin_family = AF_INET;
server_address.sin_port = htons(PORT);
server_address.sin_addr.s_addr = inet_addr("127.0.0.1");
if (connect(client_socket, (struct sockaddr *)&server_address, sizeof(server_address)) < 0)
{
printf("[!] Error when connecting!\n");
close(client_socket);
exit(EXIT_FAILURE);
}
printf("[+] Connected to the server\n");
printf("[+] Type a message and press Enter. Type 'disconnect' to quit.\n");
char input[BUFFER_SIZE];
char buffer[BUFFER_SIZE];
while (1)
{
printf("> ");
fflush(stdout);
if (fgets(input, BUFFER_SIZE, stdin) == NULL)
{
printf("[!] Error reading input\n");
break;
}
input[strcspn(input, "\n")] = '\0';
if (strlen(input) == 0)
{
continue;
}
int bytes_sent = write(client_socket, input, strlen(input));
if (bytes_sent < 0)
{
printf("[!] Error when sending data to the server!\n");
break;
}
memset(buffer, 0, BUFFER_SIZE);
int bytes_received = read(client_socket, buffer, BUFFER_SIZE - 1);
if (bytes_received <= 0)
{
printf("[!] Server closed the connection\n");
break;
}
printf("[+] Server: %s\n", buffer);
if (strncmp(input, "disconnect", strlen("disconnect")) == 0)
{
printf("[+] Disconnected from server\n");
break;
}
}
close(client_socket);
return 0;
}