I have just started an assignment in which I must create a simple server that processes http requests.
To get me started, I decided to make a basic server that waits for a connection and then continuously prints out whatever it receives from read().
Using this code to print, I expected to see a plain text http request with \r and \n replaced by <\r>
and <\n>
respectively (when I visit http://ip:port in my web browser):
char buffer[buffer_size];
size_t bytes;
while ((bytes = read(s, buffer, buffer_size - 1)) > 0) {
buffer[bytes] = '\0';
int i = 0;
while(buffer[i] != '\0') {
if (buffer[i] == '\n') {
printf("%s","<\\n>\n");
} else if (buffer[i] == '\r') {
printf("%s","<\\r>");
} else {
printf("%c",buffer[i]);
}
i++;
}
}
However, instead I just get my console spammed with alternating <\r>
and some weird square with what looks like 001B written inside (Here is a link to a picture of my terminal http://gyazo.com/13288989dc0c1f4782052a1914eb7f84). Is this a problem with my code? Does Mozilla keep spamming these intentionally?
EDIT:All of my code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define buffer_size 1024
int main(int argc, char **argv) {
int port;
int client;
struct sockaddr_in6 my_add;
struct sockaddr_in6 their_add;
socklen_t their_add_size = sizeof(their_add);
if (argc != 2) {
printf("%s\n","Usage: ./server <port>");
return -1;
}
port = atoi(argv[1]);
my_add.sin6_family = AF_INET6;
my_add.sin6_addr = in6addr_any;
my_add.sin6_port = htons(port);
int s = socket(PF_INET6, SOCK_STREAM, 0);
if (s < 0) {
printf("%s","error on socket()");
return -1;
}
if (bind (s, (struct sockaddr *) &my_add, sizeof(my_add)) != 0) {
printf("%s","error on bind()");
return -1;
}
if (listen (s, 5) != 0) {
printf("%s","error on listen()");
return -1;
}
client = accept(s, (struct sockaddr *) &their_add, &their_add_size);
printf("%s","connected");
char buffer[buffer_size];
size_t bytes;
while ((bytes = read(s, buffer, buffer_size - 1)) > 0) {
buffer[bytes] = '\0';
int i = 0;
while(buffer[i] != '\0') {
if (buffer[i] == '\n') {
printf("%s","<\\n>\n");
} else if (buffer[i] == '\r') {
printf("%s","<\\r>");
} else {
printf("%c",buffer[i]);
}
i++;
}
}
if (bytes != 0) {
printf("%s","something went wrong. bytes != 0.");
return -1;
}
printf("%s", "connection closed");
close(s);
return 0;
}