91 lines
2.4 KiB
C++
91 lines
2.4 KiB
C++
|
#include <arpa/inet.h>
|
||
|
#include <csignal>
|
||
|
#include <cstdint>
|
||
|
#include <cstdio>
|
||
|
#include <cstdlib>
|
||
|
#include <netinet/in.h>
|
||
|
#include <sys/select.h>
|
||
|
#include <sys/socket.h>
|
||
|
#include <sys/types.h>
|
||
|
#include <unistd.h>
|
||
|
|
||
|
#include <sys/time.h>
|
||
|
#include <errno.h>
|
||
|
|
||
|
int makeSocket() {
|
||
|
int sockfd;
|
||
|
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
|
||
|
perror("socket failed");
|
||
|
exit(EXIT_FAILURE);
|
||
|
}
|
||
|
return sockfd;
|
||
|
}
|
||
|
|
||
|
void bindSocketPort(int server_fd, int port) {
|
||
|
struct sockaddr_in localAddr;
|
||
|
localAddr.sin_family = AF_INET;
|
||
|
localAddr.sin_addr.s_addr = INADDR_ANY;
|
||
|
localAddr.sin_port = htons(port);
|
||
|
|
||
|
if (bind(server_fd, (struct sockaddr *)&localAddr, sizeof(localAddr)) < 0) {
|
||
|
perror("bind failed");
|
||
|
exit(EXIT_FAILURE);
|
||
|
}
|
||
|
printf("FD %d bound to port %d\n", server_fd, port);
|
||
|
}
|
||
|
|
||
|
void startListening(int server_fd) {
|
||
|
if (listen(server_fd, 3) < 0) {
|
||
|
perror("listen");
|
||
|
exit(EXIT_FAILURE);
|
||
|
}
|
||
|
printf("FD %d listening to new connections\n", server_fd);
|
||
|
}
|
||
|
|
||
|
int acceptConnection(int server_fd) {
|
||
|
int client_fd;
|
||
|
struct sockaddr_in remoteAddr;
|
||
|
size_t addrlen = sizeof(remoteAddr);
|
||
|
if ((client_fd = accept(server_fd, (struct sockaddr *)&remoteAddr, (socklen_t *)&addrlen)) < 0) {
|
||
|
perror("accept");
|
||
|
exit(EXIT_FAILURE);
|
||
|
}
|
||
|
printf("Connection from host %s, port %d, FD %d\n", inet_ntoa(remoteAddr.sin_addr), ntohs(remoteAddr.sin_port), client_fd);
|
||
|
return client_fd;
|
||
|
}
|
||
|
|
||
|
|
||
|
int main(int argc, char* argv[]) {
|
||
|
if (argc != 2) {
|
||
|
printf("Usage: %s portNumber \n", argv[0]);
|
||
|
exit(EXIT_FAILURE);
|
||
|
}
|
||
|
int port = atoi(argv[1]);
|
||
|
printf("Start socket port %d\n", port);
|
||
|
|
||
|
int server_fd = makeSocket();
|
||
|
bindSocketPort(server_fd, port);
|
||
|
startListening(server_fd);
|
||
|
int client_fd = acceptConnection(server_fd);
|
||
|
|
||
|
uint64_t bytes_read = 0;
|
||
|
uint64_t kbytes_read = 0;
|
||
|
|
||
|
while (true) {
|
||
|
char buffer[32 * 1024] = {0};
|
||
|
ssize_t bytes = read(client_fd, &buffer, sizeof(buffer));
|
||
|
|
||
|
bytes_read += static_cast<uint64_t>(bytes);
|
||
|
//printf("tot bytos %lu\n", bytes_read);
|
||
|
|
||
|
if (uint64_t newkb = (bytes_read / 1024) > 0) {
|
||
|
//printf("before: %lu", bytes_read);
|
||
|
bytes_read -= (1024 * newkb);
|
||
|
//printf("after: %lu", bytes_read);
|
||
|
kbytes_read += newkb;
|
||
|
//printf("Read %d kbytes\n", static_cast<int>(kbytes_read));
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return 0;
|
||
|
}
|