Last active
May 7, 2021 13:02
-
-
Save bluebrown/77b28457688869ca2a2cc54aa4f04817 to your computer and use it in GitHub Desktop.
Berkeley Sockets 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 <sys/socket.h> | |
#include <netdb.h> | |
#define BACKLOG 10 | |
#define PORT 8080 | |
int main(void) | |
{ | |
int sockfd, new_fd, sin_size; | |
struct sockaddr_in server, client; | |
server.sin_family = AF_INET; | |
server.sin_addr.s_addr = INADDR_ANY; | |
server.sin_port = htons(PORT); | |
if ((sockfd = socket(server.sin_family, SOCK_STREAM, 0)) == -1) | |
{ | |
perror("socket"); | |
return 2; | |
} | |
if (bind(sockfd, (struct sockaddr *)&server, sizeof(server)) < 0) | |
{ | |
perror("bind"); | |
return 2; | |
} | |
if (listen(sockfd, BACKLOG) == -1) | |
{ | |
perror("listen"); | |
return 2; | |
} | |
char msg[] = "HTTP/1.1 200 OK\r\n" | |
"content-type: text/plain\r\n" | |
"content-length: 13\r\n" | |
"\r\n" | |
"Hello, world!"; | |
while (1) | |
{ | |
sin_size = sizeof client; | |
new_fd = accept(sockfd, (struct sockaddr *)&client, &sin_size); | |
if (new_fd == -1) | |
{ | |
perror("accept"); | |
continue; | |
} | |
if (send(new_fd, msg, strlen(msg), 0) == -1) | |
perror("send"); | |
close(new_fd); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a great resource http://beej.us/guide/bgnet/html/