I found the highest rated answer helpful for understanding what needs to be done conceptually, but it falls short of helping new C/C++ developers understand how to read the header.
The trick is to realize that most TCP server examples you can find via Google stop short of showing the reader how to actually receive a request! You need to use the recv
method and read the request into something that you can parse. In the below example, I am reading that into a vector<char>
called but
(short for buffer
) and using the buf.data()
to access the underlying char array for printing to the console.
Assume you have a new socket for client...
listen(sock, 5);
while (1) {
// Make a new socket for the client that just tried to connect
client_fd = accept(sock, (struct sockaddr *) &cli_addr, &sin_len);
char buffer[1024] = {0};
int server_fd, new_socket, valread;
valread = read(sock , buffer, 1024);
std::cout << buffer << std::endl;
printf("got connection\n");
// Handle a case where you can't accept the request
if (client_fd == -1) {
perror("Can't accept");
continue;
}
// Recieve data from the new socket that we made for the client
// We are going to read the header into the vector<char>, and then
// you can implement a method to parse the header.
vector<char> buf(5000); // you are using C++ not C
int bytes = recv(client_fd, buf.data(), buf.size(), 0);
std::cout << bytes << std::endl;
std::cout << sizeof(buf);
std::cout << buf.data() << buf[0] << std::endl;
To read more about the sockets API, the Wikipedia article is a surprisingly good resource. https://en.wikipedia.org/wiki/Berkeley_sockets