77 lines
2.0 KiB
C++
77 lines
2.0 KiB
C++
#include <arpa/inet.h>
|
|
#include <cstdint>
|
|
#include <cstdio>
|
|
#include <cstdlib>
|
|
#include <netinet/in.h>
|
|
#include <sys/socket.h>
|
|
#include <sys/types.h>
|
|
#include <unistd.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 const *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);
|
|
|
|
while (true) {
|
|
uint32_t word;
|
|
ssize_t bytes = read(client_fd, &word, 4);
|
|
if (bytes != 4) {
|
|
perror("Receive failed");
|
|
exit(EXIT_FAILURE);
|
|
}
|
|
printf("[RICEVUTO]\t0x%x", word);
|
|
}
|
|
|
|
|
|
return 0;
|
|
} |