379_demos/lab3/demos/server.c

104 lines
2.1 KiB
C
Raw Normal View History

2024-10-01 16:45:02 -06:00
#include <netdb.h>
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#define PORT "1025"
#define BACKLOG 4
#define BUF_SIZE 20
int create_server_sock(char* port) {
struct addrinfo hints = {
.ai_family = AF_INET6,
.ai_socktype = SOCK_STREAM,
.ai_flags = AI_PASSIVE || AI_V4MAPPED
};
struct addrinfo *res;
int err = getaddrinfo(NULL, port, &hints, &res);
if (err != 0) {
fprintf(stderr, "gai_err %s\n", gai_strerror(err));
_exit(1);
}
int sfd;
struct addrinfo* cur = res;
for (; cur != NULL; cur = cur->ai_next) {
// create socket
sfd = socket(cur->ai_family, cur->ai_socktype, cur->ai_protocol);
if (sfd == -1) {
perror("socket");
continue;
}
int val = 1;
err = setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
if (err == -1) {
perror("setsockopt");
close(sfd);
continue;
}
// Bind
err = bind(sfd, cur->ai_addr, cur->ai_addrlen);
if (err == -1) {
perror("bind");
close(sfd);
continue;
}
// Listen
err = listen(sfd, BACKLOG);
if (err == -1) {
perror("listen");
close(sfd);
continue;
}
break;
}
freeaddrinfo(res);
if (cur == NULL) {
fprintf(stderr, "failed to create socket\n");
close(sfd);
_exit(1);
}
return sfd;
}
int main() {
int sfd = create_server_sock(PORT);
struct sockaddr_storage client_addr;
socklen_t client_addr_len = sizeof(client_addr);
int cfd = accept(sfd, (struct sockaddr*) &client_addr, &client_addr_len);
if (cfd == -1) {
perror("accept");
_exit(1);
}
int n;
uint8_t buf[BUF_SIZE];
while ((n = read(cfd, buf, BUF_SIZE)) > 0) {
if (n == -1) {
perror("read");
_exit(1);
}
if (write(STDOUT_FILENO, buf, n) == -1) {
perror("read");
_exit(1);
}
}
close(sfd);
return 0;
}