Skip to content

Instantly share code, notes, and snippets.

@udoprog
Created January 22, 2018 21:54
Show Gist options
  • Select an option

  • Save udoprog/bf2923d0cbabc5c4f059deef23155a1b to your computer and use it in GitHub Desktop.

Select an option

Save udoprog/bf2923d0cbabc5c4f059deef23155a1b to your computer and use it in GitHub Desktop.
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#define panic(EXPR, MSG) \
if (EXPR) { \
fprintf(stderr, "%s:%d: %s: %s\n", __FILE__, __LINE__, #EXPR, MSG); \
\
if (errno != 0) { \
fprintf(stderr, "errno: %s", strerror(errno)); \
} \
\
abort(); \
}
int main() {
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(8080);
int fd = socket(AF_INET, SOCK_STREAM, 0);
panic(fd == -1, "unable to open socket");
panic(bind(fd, (struct sockaddr *)&server, sizeof(server)), "failed to bind");
panic(listen(fd, 128), "failed to setup socket to listen");
panic(setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &(int){ 1 }, sizeof(int)) == 1, "failed to set option")
while (1) {
struct sockaddr_in client;
socklen_t client_len = sizeof(client);
int cfd = accept(fd, (struct sockaddr *)&client, &client_len);
char buffer[2000];
bzero(buffer, sizeof(buffer));
ssize_t read_size;
while((read_size = recv(cfd, buffer, 2000 , 0)) > 0) {
while (read_size > 0) {
ssize_t sent = send(cfd, buffer, read_size, 0);
panic(sent < 0, "could not send data");
read_size -= sent;
}
}
panic(read_size < 0, "failed to read");
}
close_fd:
close(fd);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment