Initial server receiving

This commit is contained in:
akp 2023-11-01 13:36:33 +00:00
parent 672d883974
commit 6bd93b93b0
No known key found for this signature in database
GPG key ID: CF8D58F3DEB20755

View file

@ -1,6 +1,76 @@
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
int main (int argc, char **argv) {
// Server to be written
int open_socket(const char *ip, const char *port, int *res_sd) {
// get address info
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 (bind(sd, addrinfo_res->ai_addr, addrinfo_res->ai_addrlen) == -1) {
perror("failed to bind to port");
return 1;
}
if (listen(sd, 5)) {
perror("failed to start listening for connections");
return 1;
}
*res_sd = sd;
freeaddrinfo(addrinfo_res);
return 0;
}
int main (int argc, char **argv) {
if (argc < 2) {
fprintf(stderr, "Usage: %s PORT\n", argv[0]);
return 1;
}
char *port_str = argv[1];
int sd;
if (open_socket("127.0.0.1", port_str, &sd) != 0) {
return 1;
}
int new_sd = accept(sd, NULL, NULL);
if (new_sd == -1) {
perror("failed to accept new connection");
return 1;
}
char *dat = (char *) malloc(sizeof(char) * 128);
int num_bytes = recv(new_sd, dat, 128, 0);
do {
if (num_bytes == -1) {
perror("failed to receive from remote host");
return 1;
}
printf("%s", dat);
} while ((num_bytes = recv(new_sd, dat, 128, 0)) != 0);
return 0;
}