bpaul-http

http server that will eventually be used for bpaul.xyz
Log | Files | Refs | README

tcp.c (1599B)


      1 #include <arpa/inet.h>
      2 #include <errno.h>
      3 #include <netinet/in.h>
      4 #include <netinet/ip.h>
      5 #include <stdbool.h>
      6 #include <stdio.h>
      7 #include <stdlib.h>
      8 #include <string.h>
      9 #include <sys/socket.h>
     10 #include <sys/stat.h>
     11 #include <unistd.h>
     12 
     13 #define PORT    8000
     14 #define BACKLOG 50
     15 
     16 #define BUF_SIZE 1024
     17 
     18 int
     19 create_socket() {
     20 	int sock;
     21 	struct sockaddr_in addr, public_addr;
     22 
     23 	/* Create a socket that is tcp or something */
     24 	if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
     25 		perror("socket");
     26 		exit(1);
     27 	}
     28 
     29 	setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &(int){1}, sizeof(int));
     30 
     31 	addr.sin_family = AF_INET;
     32 	addr.sin_port   = htons(PORT);
     33 	if (!inet_aton("0.0.0.0", &addr.sin_addr)) {
     34 		perror("inet_aton addr");
     35 		exit(1);
     36 	}
     37 
     38 	/* Bind the socket to an address */
     39 	if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
     40 		perror("bind");
     41 		exit(1);
     42 	}
     43 
     44 	/* Listen for connections on the socket */
     45 	if (listen(sock, BACKLOG) == -1) {
     46 		perror("listen");
     47 		exit(1);
     48 	}
     49 
     50 	return sock;
     51 }
     52 
     53 int
     54 accept_socket(int sock) {
     55 	int asock;
     56 	struct sockaddr_in peer_addr;
     57 	socklen_t peer_addr_size;
     58 
     59 	peer_addr_size = sizeof(peer_addr);
     60 	asock = accept(sock, (struct sockaddr *)&peer_addr, &peer_addr_size);
     61 
     62 	return asock;
     63 }
     64 
     65 char *
     66 read_socket(int sock) {
     67 	char *buf, *buf2;
     68 	ssize_t read_size, cur_size = 0;
     69 
     70 	buf  = calloc(BUF_SIZE, 1);
     71 	buf2 = calloc(BUF_SIZE, 1);
     72 
     73 	/* Keep reading until done */
     74 	do {
     75 		read_size = recv(sock, buf2, BUF_SIZE, 0);
     76 		cur_size += read_size;
     77 
     78 		buf = realloc(buf, cur_size + 1);
     79 		strcat(buf, buf2);
     80 	} while (read_size == BUF_SIZE);
     81 
     82 	free(buf2);
     83 
     84 	return buf;
     85 }