2021-05-21 11:07:13 +02:00
|
|
|
#include <arpa/inet.h>
|
|
|
|
#include <stdio.h>
|
|
|
|
#include <stdlib.h>
|
|
|
|
#include <string.h>
|
|
|
|
#include <sys/socket.h>
|
|
|
|
#include <sys/types.h>
|
|
|
|
|
|
|
|
void handle_arguments(int argc, char *argv[]) {
|
|
|
|
if (argc != 2) {
|
|
|
|
fprintf(stderr, "Usage: %s PORT\n", argv[0]);
|
|
|
|
exit(EXIT_FAILURE);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-05-15 20:56:56 +02:00
|
|
|
void run_server(int port) {
|
2021-05-21 11:07:13 +02:00
|
|
|
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
|
|
|
|
if (sockfd < 0) {
|
|
|
|
fprintf(stderr, "socket: ");
|
|
|
|
exit(EXIT_FAILURE);
|
|
|
|
}
|
|
|
|
|
|
|
|
struct sockaddr_in serv_addr, client_addr;
|
|
|
|
socklen_t client_addr_len;
|
|
|
|
memset(&serv_addr, 0, sizeof(serv_addr));
|
|
|
|
memset(&client_addr, 0, sizeof(client_addr));
|
|
|
|
serv_addr.sin_family = AF_INET;
|
|
|
|
serv_addr.sin_port = htons(port);
|
|
|
|
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
|
|
|
|
|
|
|
|
int rv = bind(sockfd, (const struct sockaddr *)&serv_addr, sizeof(serv_addr));
|
|
|
|
if (rv < 0) {
|
|
|
|
fprintf(stderr, "bind: ");
|
|
|
|
exit(EXIT_FAILURE);
|
|
|
|
}
|
|
|
|
|
|
|
|
rv = listen(sockfd, 5);
|
|
|
|
if (rv < 0) {
|
|
|
|
fprintf(stderr, "listen: ");
|
|
|
|
exit(EXIT_FAILURE);
|
|
|
|
}
|
|
|
|
|
|
|
|
int accfd = accept(sockfd, (struct sockaddr *)&client_addr, &client_addr_len);
|
|
|
|
if (accfd < 0) {
|
|
|
|
fprintf(stderr, "accept: ");
|
|
|
|
exit(EXIT_FAILURE);
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
size_t buffer_size = 100;
|
|
|
|
char buffer[buffer_size];
|
|
|
|
memset(&buffer, 0, buffer_size);
|
|
|
|
|
|
|
|
while (1) {
|
|
|
|
read(accfd, buffer, buffer_size);
|
|
|
|
write(accfd, buffer, buffer_size);
|
|
|
|
memset(&buffer, 0, buffer_size);
|
|
|
|
}
|
2021-05-15 20:56:56 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
int main(int argc, char *argv[]) {
|
|
|
|
// Socket
|
|
|
|
// setsockopt
|
|
|
|
// Bind
|
|
|
|
// listen()
|
|
|
|
// accept
|
|
|
|
// send/recv
|
2021-05-21 11:07:13 +02:00
|
|
|
handle_arguments(argc, argv);
|
|
|
|
run_server(strtol(argv[1], NULL, 10));
|
2021-05-15 20:56:56 +02:00
|
|
|
|
|
|
|
return 0;
|
|
|
|
}
|