First commit
This commit is contained in:
95
ch1/TCPEchoServer4.c
Normal file
95
ch1/TCPEchoServer4.c
Normal file
@@ -0,0 +1,95 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/socket.h>
|
||||
#include <netinet/in.h>
|
||||
#include <arpa/inet.h>
|
||||
|
||||
#include "Practical.h"
|
||||
#include "TCPServerUtility.h"
|
||||
|
||||
static const int MAXPENDING = 5;
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
if (argc != 2) {
|
||||
DieWithUserMessage("Parameter(s)", "<Server Port>");
|
||||
}
|
||||
|
||||
const in_port_t server_port = atoi(argv[1]);
|
||||
|
||||
const int server_sock = socket(AF_INET, SOCK_STREAM, proto_get_num("tcp"));
|
||||
if (server_sock < 0) {
|
||||
DieWithSystemMessage("socket() failed");
|
||||
}
|
||||
|
||||
struct sockaddr_in server_addr = {
|
||||
.sin_family = AF_INET,
|
||||
.sin_addr = {
|
||||
.s_addr = htonl(INADDR_ANY),
|
||||
},
|
||||
.sin_port = htons(server_port)
|
||||
};
|
||||
|
||||
int ret_val = bind(
|
||||
server_sock,
|
||||
(struct sockaddr *) &server_addr,
|
||||
sizeof(server_addr)
|
||||
);
|
||||
if (ret_val < 0) {
|
||||
DieWithSystemMessage("bind() failed");
|
||||
}
|
||||
|
||||
ret_val = listen(server_sock, MAXPENDING);
|
||||
if (ret_val < 0) {
|
||||
DieWithSystemMessage("listen() failed");
|
||||
} else {
|
||||
char server_name[INET_ADDRSTRLEN];
|
||||
const char *ntop_res = inet_ntop(
|
||||
AF_INET,
|
||||
&server_addr.sin_addr.s_addr,
|
||||
server_name,
|
||||
sizeof(server_name)
|
||||
);
|
||||
if (ntop_res != NULL) {
|
||||
printf("Listening on %s/%d...\n", server_name, server_port);
|
||||
} else {
|
||||
puts("Unable to get server address");
|
||||
}
|
||||
}
|
||||
|
||||
while (1) {
|
||||
struct sockaddr_in client_addr;
|
||||
socklen_t client_addr_len = sizeof(client_addr);
|
||||
|
||||
int client_sock = accept(
|
||||
server_sock,
|
||||
(struct sockaddr *) &client_addr,
|
||||
&client_addr_len
|
||||
);
|
||||
if (client_sock < 0) {
|
||||
DieWithSystemMessage("accept() failed");
|
||||
}
|
||||
|
||||
char client_name[INET_ADDRSTRLEN];
|
||||
const char *ntop_res = inet_ntop(
|
||||
AF_INET,
|
||||
&client_addr.sin_addr.s_addr,
|
||||
client_name,
|
||||
sizeof(client_name)
|
||||
);
|
||||
if (ntop_res != NULL) {
|
||||
printf(
|
||||
"Handling client %s/%d\n",
|
||||
client_name,
|
||||
ntohs(client_addr.sin_port)
|
||||
);
|
||||
} else {
|
||||
puts("Unable to get client address");
|
||||
}
|
||||
|
||||
HandleTCPClient(client_sock);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user