Created
June 12, 2020 04:30
-
-
Save bmcculley/430633537c8a1e8f7ac78c8b9caa1ba7 to your computer and use it in GitHub Desktop.
example c server
This file contains hidden or 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 <stdlib.h> | |
#include <unistd.h> | |
#include <sys/types.h> | |
#include <sys/socket.h> | |
#include <netinet/in.h> | |
#include <netdb.h> | |
#include <arpa/inet.h> | |
#include <err.h> | |
char response[] = "HTTP/1.1 200 OK\r\n" | |
"Server: hello\r\n" | |
"Content-Type: text/html; charset=UTF-8\r\n\r\n" | |
"<!DOCTYPE html><html><head><title>hello!</title>" | |
"</head>" | |
"<body><h1>hello, world!</h1></body></html>\r\n" | |
"<p>Just a quick example of a web server...</p>"; | |
int main() | |
{ | |
int one = 1, client_fd; | |
struct sockaddr_in svr_addr, cli_addr; | |
socklen_t sin_len = sizeof(cli_addr); | |
int sock = socket(AF_INET, SOCK_STREAM, 0); | |
if (sock < 0) | |
err(1, "can't open socket"); | |
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int)); | |
int port = 8080; | |
svr_addr.sin_family = AF_INET; | |
svr_addr.sin_addr.s_addr = INADDR_ANY; | |
svr_addr.sin_port = htons(port); | |
if (bind(sock, (struct sockaddr *) &svr_addr, sizeof(svr_addr)) == -1) { | |
close(sock); | |
err(1, "Can't bind"); | |
} | |
listen(sock, 5); | |
while (1) { | |
client_fd = accept(sock, (struct sockaddr *) &cli_addr, &sin_len); | |
char *ip = inet_ntoa(cli_addr.sin_addr); | |
printf("connection from: %s\n", ip); | |
if (client_fd == -1) { | |
perror("Can't accept"); | |
continue; | |
} | |
write(client_fd, response, sizeof(response) - 1); /*-1:'\0'*/ | |
close(client_fd); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment