Created
November 5, 2020 15:55
-
-
Save altilunium/492489a33c8e4c6aa3f52e43c2fecc11 to your computer and use it in GitHub Desktop.
WebServer in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <netdb.h> | |
#include <netinet/in.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <sys/socket.h> | |
#include <sys/types.h> | |
#define MAX 1000 | |
#define PORT 8080 | |
#define SA struct sockaddr | |
int main(){ | |
int sockfd, connfd, len; | |
struct sockaddr_in servaddr, cli; | |
char buff[MAX]; | |
sockfd = socket(AF_INET, SOCK_STREAM, 0); | |
bzero(&servaddr, sizeof(servaddr)); | |
servaddr.sin_family = AF_INET; | |
servaddr.sin_addr.s_addr = htonl(INADDR_ANY); | |
servaddr.sin_port = htons(PORT); | |
bind(sockfd, (SA*)&servaddr, sizeof(servaddr)); | |
listen(sockfd, 5); | |
len = sizeof(cli); | |
for(;;){ | |
connfd = accept(sockfd, (SA*)&cli, &len); | |
printf("New visitor!\n"); | |
printf("IP : %d\n",ntohl(cli.sin_addr.s_addr)); | |
printf("Port : %d\n",ntohs(cli.sin_port)); | |
bzero(buff,MAX); | |
read(connfd,buff,sizeof(buff)); | |
printf("%s",buff); | |
if (strncmp("\0",buff,1) != 0) { | |
bzero(buff, MAX); | |
strncpy(buff,"HTTP/1.1 400 Bad Request\nServer: Altilunium-WebServer (Ubuntu)\nContent-Length: 301\nConnection: close\nContent-Type: text/html\n\n<html><head><title>Altilunium-WebServer</title></head><body><h1>Altilunium-WebServer</h1><p>It's working!<br /></p><hr></body></html>",1000); | |
write(connfd, buff, sizeof(buff)); | |
} | |
bzero(buff, MAX); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment