Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#define BACKLOG 100
int sockfd;
void create_and_bind() {
int portf=8880;
int yes=1;
struct sockaddr_in my_addr;
if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
if (setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(int)) == -1) {
perror("setsockopt");
exit(1);
}
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(portf);
my_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
memset(&(my_addr.sin_zero), '\0', 8);
if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) {
perror("bind");
exit(1);
}
if (listen(sockfd, BACKLOG) == -1) {
perror("listen");
exit(1);
}
}
int main(void) {
char in[3000], sent[1024], code[50], mime[100];
char *result;
char *json="{\"var1\":\"value1\"}";
int new_fd;
struct sockaddr_in their_addr;
create_and_bind();
while(1) {
socklen_t sin_size = sizeof(struct sockaddr_in);
if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size)) == -1) {
perror("accept");
continue;
}
if (read(new_fd, in, sizeof(in)) == -1) {
perror("recive");
continue;
}
result = strtok(in, " ");
result = strtok(NULL, " ");
printf("result=%s\n",result);
strcpy (mime, "application/json");
strcpy (code, "200 OK");
sprintf(sent,"HTTP/1.1 %s\r\n",code);
sprintf(sent+strlen(sent),"Server: picohttpd 0.1.0\r\n");
sprintf(sent+strlen(sent), "Content-Length: %d\r\n",(int)strlen(json));
sprintf(sent+strlen(sent), "Connection: close\r\n");
sprintf(sent+strlen(sent), "Content-Type: %s; charset=utf-8\r\n\r\n",mime);
sprintf(sent+strlen(sent), "%s",json);
if (write(new_fd, sent, strlen(sent))<1){
}
close(new_fd);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.