-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcp_client.c
61 lines (48 loc) · 1.49 KB
/
tcp_client.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
#include <arpa/inet.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
int main(void) {
int socket_desc;
struct sockaddr_in server_addr;
char server_message[100], client_message[100];
// Clean buffers:
memset(server_message, '\0', sizeof(server_message));
memset(client_message, '\0', sizeof(client_message));
// Create socket:
socket_desc = socket(AF_INET, SOCK_STREAM, 0);
if (socket_desc < 0) {
printf("Unable to create socket\n");
return -1;
}
printf("Socket created successfully\n");
// Set port and IP the same as server-side:
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(2000);
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
// Send connection request to the Server:
if (connect(socket_desc, (struct sockaddr *)&server_addr,
sizeof(server_addr)) < 0) {
printf("Unable to connect!\n");
return -1;
}
printf("Connected to Server succesfully.\n");
// Get input from user
printf("Enter message: ");
gets(client_message);
// Send message to server
if (send(socket_desc, client_message, strlen(client_message), 0) < 0) {
printf("Unable to send message.\n");
return -1;
}
// Revieve server's response.
if (recv(socket_desc, server_message, sizeof(server_message), 0) < 0) {
printf("Error while receiving server's msg\n");
return -1;
}
printf("Server's response: %s\n", server_message);
// Close the socket:
close(socket_desc);
return 0;
}