Skip to content

Instantly share code, notes, and snippets.

@aneury1
Created November 2, 2017 02:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aneury1/d730f6a4ba4ba38984fc3b311e37067a to your computer and use it in GitHub Desktop.
Save aneury1/d730f6a4ba4ba38984fc3b311e37067a to your computer and use it in GitHub Desktop.
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <iostream>
using namespace std;
const char *response ="HTTP/1.1 404 Not Found\n"\
"Date: Sun, 18 Oct 2012 10:36:20 GMT\n"\
"Server: Apache/2.2.14 (Win32)\n"\
"Content-Length: 230\n"\
"Connection: Closed\n"
"Content-Type: text/html; charset=iso-8859-1\n\n"
"<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n"
"<html>\n"
"<head>\n"
" <title>404 Not Found</title>\n"
"</head>\n"
"<body>\n"
" <h1>Not Found</h1>\n"
" <p>The requested URL /t.html was not found on this server.</p>\n"
"<form>\n<input type=\"text\"/></form>"
"</body>\n"
"</html>\n";
int
main(int argc, char **argv)
{
struct sockaddr_in server_addr,client_addr;
socklen_t clientlen = sizeof(client_addr);
int option, port, reuse;
int server, client;
char *buf;
int buflen;
int nread;
// setup default arguments
port = 26264;
// process command line options using getopt()
// see "man 3 getopt"
while ((option = getopt(argc,argv,"p:")) != -1) {
switch (option) {
case 'p':
port = atoi(optarg);
break;
default:
cout << "server [-p port]" << endl;
exit(EXIT_FAILURE);
}
}
// setup socket address structure
memset(&server_addr,0,sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port);
server_addr.sin_addr.s_addr = INADDR_ANY;
// create socket
server = socket(PF_INET,SOCK_STREAM,0);
if (!server) {
perror("socket");
exit(-1);
}
// set socket to immediately reuse port when the application closes
reuse = 1;
if (setsockopt(server, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0) {
perror("setsockopt");
exit(-1);
}
// call bind to associate the socket with our local address and
// port
if (bind(server,(const struct sockaddr *)&server_addr,sizeof(server_addr)) < 0) {
perror("bind");
exit(-1);
}
// convert the socket to listen for incoming connections
if (listen(server,SOMAXCONN) < 0) {
perror("listen");
exit(-1);
}
// allocate buffer
buflen = 1024;
buf = new char[buflen+1];
// accept clients
while ((client = accept(server,(struct sockaddr *)&client_addr,&clientlen)) > 0) {
// loop to handle all requests
while (1) {
// read a request
memset(buf,0,buflen);
nread = recv(client,buf,buflen,0);
if (nread == 0)
break;
printf("%s\n", buf);
// send a response
printf("Response\n%s", response);
send(client, response, strlen(response), 0);
}
close(client);
}
close(server);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment