Complete client implementation
This commit is contained in:
parent
eb32875748
commit
784dd1ca22
1 changed files with 51 additions and 1 deletions
|
@ -1,6 +1,8 @@
|
|||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/socket.h>
|
||||
#include <netdb.h>
|
||||
|
||||
#define USAGE "usage: %s IP PORT OPCODE [ARGS...]\n"
|
||||
|
||||
|
@ -67,7 +69,55 @@ int main (int argc, char **argv) {
|
|||
free(payload);
|
||||
}
|
||||
|
||||
fwrite(message, 1, 2 + payload_size, stdout);
|
||||
// fwrite(message, 1, 2 + payload_size, stdout);
|
||||
|
||||
|
||||
|
||||
struct addrinfo addr_spec;
|
||||
struct addrinfo *addrinfo_res;
|
||||
|
||||
memset(&addr_spec, 0, sizeof(addr_spec));
|
||||
addr_spec.ai_family = AF_UNSPEC;
|
||||
addr_spec.ai_socktype = SOCK_STREAM;
|
||||
|
||||
int addrinfo_status = getaddrinfo(ip, port, &addr_spec, &addrinfo_res);
|
||||
if (addrinfo_status != 0) {
|
||||
fprintf(stderr, "get address info: %s\n", gai_strerror(addrinfo_status));
|
||||
return 1;
|
||||
}
|
||||
|
||||
int sd = socket(addrinfo_res->ai_family, addrinfo_res->ai_socktype, addrinfo_res->ai_protocol);
|
||||
|
||||
if (sd == -1) {
|
||||
perror("failed to open socket");
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (connect(sd, addrinfo_res->ai_addr, addrinfo_res->ai_addrlen) == -1) {
|
||||
perror("failed to connect");
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (send(sd, message, 2 + payload_size, 0) == -1) {
|
||||
perror("failed to write to remote");
|
||||
return 1;
|
||||
}
|
||||
|
||||
char *buf = (char *)malloc(sizeof(char) * 128);
|
||||
int num_bytes;
|
||||
while ((num_bytes = recv(sd, buf, 128, 0)) != 0) {
|
||||
if (num_bytes == -1) {
|
||||
perror("failed to read from remote");
|
||||
return 1;
|
||||
}
|
||||
fwrite(buf, 1, num_bytes, stdout);
|
||||
}
|
||||
|
||||
printf("\n");
|
||||
|
||||
free(buf);
|
||||
free(message);
|
||||
freeaddrinfo(addrinfo_res);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
|
Reference in a new issue