I got a task to implement a http server in c code. it should include handling several connections, but for now I just want to make sure it works with just a single connection. first, here is my code:
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#define BUF_SIZE 1025
int main(int argc, char **argv)
{
uint16_t portNum = 80;
int connfd = 0, listenFd;
struct sockaddr_in serv_addr, peer_addr;
if ((listenFd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("socket syscall failed: %s.\nExiting...\n", strerror(errno));
exit(EXIT_FAILURE);
}
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(portNum);
if (bind(listenFd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)))
{
printf("bind syscall failed: %s\nExiting...\n", strerror(errno));
exit(EXIT_FAILURE);
}
if (listen(listenFd, 5))
{
printf("listen syscall failed: %s\nExiting...\n", strerror(errno));
exit(EXIT_FAILURE);
}
while (1)
{
/* new connection */
socklen_t addrsize = sizeof(struct sockaddr_in);
connfd = accept(listenFd, (struct sockaddr *) &peer_addr, &addrsize);
if (connfd < 0)
{
printf("\n Error : Accept Failed. %s \n", strerror(errno));
return 1;
}
char httpRequest[BUF_SIZE] = {0};
if ((recv(connfd, httpRequest, BUF_SIZE, 0)) == -1)
{
printf("recv syscall failed: %s\nExiting...\n", strerror(errno));
exit(EXIT_FAILURE);
}
char msg[BUF_SIZE] = {0};
strcpy(msg, "200 OK THIS IS A TEST");
printf("sending message...\n");
int len = strlen(msg);
if (send(connfd, msg, len, 0) < 0)
{
printf("SEND ERROR\n");
exit(EXIT_FAILURE);
}
printf("message sent!\n");
close(connfd);
close(listenFd);
// THIS IS FOR DEBUG - ignore...
return 0;
}
return EXIT_SUCCESS;
}
here's my problem: to test my code I ran the following command in another linux terminal:
curl -v loaclhost:80/~/ex.txt
(where ex.txt is simply a test file...) here is the problem: I see the http request both in the server and in the curl output, but it seems like the "send" command of the server doesn't work - in the curl window beneath the http rquest it says:
* Empty reply from server
* Connection #0 to host localhost left intact
curl: (52) Empty reply from server
any ideas?