-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.c
More file actions
75 lines (64 loc) · 2.05 KB
/
client.c
File metadata and controls
75 lines (64 loc) · 2.05 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
#define _POSIX_C_SOURCE 201712L
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdbool.h>
#define INP_SIZE 256 // Size of the message must not 256 bytes
int open_clientfd(char *hostname, char *port) {
int clientfd;
struct addrinfo hints, *listp, *p;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_socktype = SOCK_STREAM; /* Open a connection */
hints.ai_flags = AI_NUMERICSERV; /* Use numeric port arg */
hints.ai_flags |= AI_ADDRCONFIG; /* Recommended for connections */
getaddrinfo(hostname, port, &hints, &listp);
/* Walk the list for one that we can successfully connect to */
for(p = listp; p; p = p->ai_next) {
/* Create a socket descriptor*/
if((clientfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) < 0) {
continue; /* Socket failed, try the next*/
}
/* Connect to the server */
if (connect(clientfd, p->ai_addr, p->ai_addrlen) != -1) {
break; /* Success */
}
close(clientfd); /* Connect failed, try another */
}
/* Clean up */
freeaddrinfo(listp);
if (!p){ /* All connects failed */
return-1;
} else { /* The last connect succeeded */
return clientfd;
}
}
int main(int argc, char **argv) {
int clientfd;
char *host, *port, buf[INP_SIZE];
host = argv[1];
port = argv[2];
clientfd= open_clientfd(host, port);
char inp[INP_SIZE];
while (true) {
printf("> "); // get command
fflush(stdout);
char output[INP_SIZE];
memset(output, 0, sizeof(output));
// Parse argv from input
fgets(inp, INP_SIZE, stdin);
// Commands
if (strstr(inp, "quit")) {
write(clientfd, inp, strlen(inp));
close(clientfd);
break;
}else{
write(clientfd, inp, strlen(inp));
read(clientfd, output, INP_SIZE);
printf("%s\n", output);
}
}
}