This is a simple sever written in C++ and the original code can be found in “The definitive guide to Linux network programming” book.
#include <stdio.h>
#include <stdlib.h>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
const char APRESSMESSAGE[] = "APRESS - For Professionals, by Professionals!\n";
int main(int argc, char *argv[])
{
int simpleSocket = 0;
int simplePort = 0;
int returnStatus = 0;
struct sockaddr_in simpleServer;
// make sure we va a port number
if (argc != 2){
fprintf(stderr, "Usage: %s <port>\n", argv[0]);
exit(1);
}
// Create streaming socket
simpleSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (simpleSocket == -1){
fprintf(stderr, "Could not create a socket!\n");
exit(1);
}
else {
fprintf(stderr, "Socket created!\n");
}
// retrieve the port number for listing
simplePort = atoi(argv[1]);
// Set up address strucuter
//use INADDR_ANY
std::memset(&simpleServer, '\0',sizeof(simpleServer));
simpleServer.sin_family = AF_INET;
simpleServer.sin_addr.s_addr = htonl(INADDR_ANY);
simpleServer.sin_port = htons(simplePort);
returnStatus = bind(simpleSocket, (struct sockaddr*)&simpleServer, sizeof(simpleServer));
if (returnStatus == 0){
fprintf(stderr, "Bind Completed!\n");
}
else {
fprintf(stderr, "Could not bid the address!\n");
close(simpleSocket);
exit(1);
}
// Listen on the socket for connection
returnStatus = listen(simpleSocket, 5);
if (returnStatus == -1){
fprintf(stderr, "Cannot listen to socket\n!");
close(simpleSocket);
exit(1);
}
while(1) {
struct sockaddr_in clientName = { 0};
int simpleChildSocket = 0;
socklen_t clientNameLength = sizeof(clientName);
simpleChildSocket = accept(simpleSocket, (struct sockaddr *)&clientName, &clientNameLength);
if (simpleChildSocket == -1){
fprintf(stderr, "Cannot accept connections!\n");
close(simpleSocket);
exit(1);
}
write(simpleChildSocket, APRESSMESSAGE, strlen(APRESSMESSAGE));
close(simpleChildSocket);
}
close(simpleSocket);
return 0;
}