Last active
July 22, 2017 14:20
-
-
Save peterdn/b7f01b5c3f923b030d000f181270f8f2 to your computer and use it in GitHub Desktop.
C HTTP response
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 <sys/socket.h> | |
#include <netinet/in.h> | |
#include <unistd.h> | |
#include <string.h> | |
#define BUF_SIZE 1000000 | |
int main(int argc, char *argv[]) { | |
int listen_socket, client_socket; | |
if (!(listen_socket = socket(AF_INET, SOCK_STREAM, 0))) { | |
printf("Couldn't create socket\n"); | |
exit(EXIT_FAILURE); | |
} | |
struct sockaddr_in addr = { | |
.sin_family = AF_INET, | |
.sin_port = htons(8060), | |
.sin_addr.s_addr = INADDR_ANY, | |
.sin_zero = "\0" | |
}; | |
if (bind(listen_socket, (struct sockaddr *) &addr, sizeof(addr)) != 0) { | |
printf("Coulnd't bind to address\n"); | |
exit(EXIT_FAILURE); | |
} | |
if (listen(listen_socket, 0) != 0) { | |
printf("Failed to listen\n"); | |
exit(EXIT_FAILURE); | |
} | |
if (!(client_socket = accept(listen_socket, NULL, NULL))) { | |
printf("Failed to accept\n"); | |
exit(EXIT_FAILURE); | |
} | |
char *header = "HTTP/1.1 200 OK\nContent-Type: image/jpeg\nContent-Length: 1000000\n\n"; | |
char payload[BUF_SIZE] = ""; | |
write(client_socket, header, strlen(header)); | |
if (send(client_socket, payload, BUF_SIZE, 0) != BUF_SIZE) { | |
printf("Failed to write all data!\n"); | |
} | |
sleep(1); | |
shutdown(client_socket, SHUT_RDWR); | |
close(client_socket); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment