Skip to content

Instantly share code, notes, and snippets.

@nieldeokar
Last active August 13, 2021 03:22
Show Gist options
  • Save nieldeokar/a044db6b751d5df9c5b309fd62d67a3d to your computer and use it in GitHub Desktop.
Save nieldeokar/a044db6b751d5df9c5b309fd62d67a3d to your computer and use it in GitHub Desktop.
Simple Apache server to identify difference between socket and port
/*
* @author : Nilesh Deokar/ @nieldeokar
* instructions :
* 1. compile using 'gcc -Wall -o apache Apache_Server.c'
* 2. run ./apache
*/
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <stdlib.h>
#define PORT 8080
char good_response_header[] = "HTTP/1.1 200 OK\r\n"
"Content-Length: %d\r\n"
"Content-Type: text/html; charset=UTF-8\r\n\r\n";
char good_response_body[] = "<!DOCTYPE HTML>"
"<html><head>"
"<title>@nieldeokar | Apache</title>"
"</head><body>"
"<h1>Apache Response</h1>"
"<p>%s"
"%s </br>"
"<font color=\"red\">%s </font></br></p>"
"</body></html>";
int main(int argc, char **argv) {
int req_bind , sockfd;
struct sockaddr_in serv_ip_address;
if((sockfd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1){
printf("Could not create socket (%s)\n",strerror(sockfd));
return 0; }
serv_ip_address.sin_family = AF_INET; // bind and listen
serv_ip_address.sin_addr.s_addr = INADDR_ANY;
serv_ip_address.sin_port = htons(PORT);
if ((req_bind = bind(sockfd, (struct sockaddr *)&serv_ip_address, sizeof(serv_ip_address))) < 0){
printf("Error occurred during binding (%s)\n",strerror(req_bind));
return 0; }
printf("Apache Listening on port %d\n", PORT);
listen(sockfd,10);
while(1) { // loop for connections
struct sockaddr_in cli_ip_address, host_address;
socklen_t ip_len = sizeof(cli_ip_address);
int cli_fd = accept(sockfd, (struct sockaddr *) &cli_ip_address, &ip_len);
if (cli_fd < 0){
printf("Error occurred during accept :%s\n",strerror(sockfd));
return 0; }
if(fork()>1){
ip_len = sizeof(host_address);
getsockname(cli_fd, (struct sockaddr *)&host_address, &ip_len);
char line1[1024], line2[1024], line3[400];
sprintf(line1," Incoming client connection from [%s:%d]", inet_ntoa(cli_ip_address.sin_addr), cli_ip_address.sin_port); // get client ip:PORT
sprintf(line2," to server [%s:%d]\n", inet_ntoa(host_address.sin_addr), htons(serv_ip_address.sin_port));
sprintf(line3,"Client socket id : %d \n", cli_fd);
printf("%s %s %s", line1,line2,line3);
char formatted_body[4096];
char formatted_header[1024];
sprintf(formatted_body,good_response_body,line1,line2,line3);
sprintf(formatted_header,good_response_header,strlen(formatted_body));
char response[strlen(formatted_body) + strlen(formatted_header)];
strcpy(response,formatted_header);
strcat(response,formatted_body);
write(cli_fd, response, strlen(response));
close(cli_fd);
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment