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>
|
2021-05-30 20:25:49 +02:00
|
|
|
#include <unistd.h>
|
2021-05-21 11:07:13 +02:00
|
|
|
|
|
|
|
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-30 20:25:49 +02:00
|
|
|
// create a socket using Internet protocol
|
2021-05-21 11:07:13 +02:00
|
|
|
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
|
2021-05-30 20:25:49 +02:00
|
|
|
if (sockfd == -1) {
|
|
|
|
perror("socket");
|
2021-05-21 11:07:13 +02:00
|
|
|
exit(EXIT_FAILURE);
|
|
|
|
}
|
|
|
|
|
2021-05-30 20:25:49 +02:00
|
|
|
|
2021-05-21 11:07:13 +02:00
|
|
|
struct sockaddr_in serv_addr, client_addr;
|
2021-05-30 20:25:49 +02:00
|
|
|
socklen_t client_addr_len = sizeof(client_addr);
|
2021-05-21 11:07:13 +02:00
|
|
|
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);
|
|
|
|
|
2021-05-30 20:25:49 +02:00
|
|
|
// bind sockfd to serv_addr
|
2021-05-21 11:07:13 +02:00
|
|
|
int rv = bind(sockfd, (const struct sockaddr *)&serv_addr, sizeof(serv_addr));
|
2021-05-30 20:25:49 +02:00
|
|
|
if (rv == -1) {
|
|
|
|
perror("bind");
|
2021-05-21 11:07:13 +02:00
|
|
|
exit(EXIT_FAILURE);
|
|
|
|
}
|
|
|
|
|
|
|
|
rv = listen(sockfd, 5);
|
2021-05-30 20:25:49 +02:00
|
|
|
if (rv == -1) {
|
|
|
|
perror("listen");
|
2021-05-21 11:07:13 +02:00
|
|
|
exit(EXIT_FAILURE);
|
|
|
|
}
|
|
|
|
|
|
|
|
int accfd = accept(sockfd, (struct sockaddr *)&client_addr, &client_addr_len);
|
2021-05-30 20:25:49 +02:00
|
|
|
if (accfd == -1) {
|
|
|
|
perror("accept");
|
2021-05-21 11:07:13 +02:00
|
|
|
exit(EXIT_FAILURE);
|
|
|
|
}
|
|
|
|
|
2021-05-30 20:25:49 +02:00
|
|
|
size_t buffer_size = sizeof(uint32_t);
|
|
|
|
union {
|
|
|
|
uint32_t number;
|
|
|
|
char array[buffer_size];
|
|
|
|
} buffer;
|
2021-05-21 11:07:13 +02:00
|
|
|
memset(&buffer, 0, buffer_size);
|
|
|
|
|
|
|
|
while (1) {
|
2021-05-30 20:25:49 +02:00
|
|
|
read(accfd, buffer.array, buffer_size);
|
|
|
|
printf("%d\n", ntohl(buffer.number));
|
|
|
|
write(accfd, buffer.array, buffer_size);
|
2021-05-21 11:07:13 +02:00
|
|
|
memset(&buffer, 0, buffer_size);
|
|
|
|
}
|
2021-05-15 20:56:56 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
int main(int argc, char *argv[]) {
|
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;
|
|
|
|
}
|