Since I am a unixUnix newbie, I wanted to know if the code reflects the "unix" style and if there is something to add for it to be robust.
P. S.: I hope I am not overusing assert
calls.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define whaterror strerror(errno)
#define PORT 0xbb8
#define BACKLOG 0xf // can't be > 128.
#define BUFFSIZE 0x400
void init_server(struct sockaddr_in* server)
{
assert(server != NULL && "Server pointer can't be null");
server -> sin_family = AF_INET; // use IP.
server -> sin_addr.s_addr = INADDR_ANY; // listen on any address (0.0.0.0).
server -> sin_port = htons(PORT); // listen on PORT.
}
int main()
{
struct sockaddr_in sock_in; // an inbound socket
const int sockfd = socket(PF_INET, SOCK_STREAM, 0); // try to open the socket.
assert(sockfd >= 0 && "Error in opening socket."); // check if socket opened.
memset((char*)&sock_in, 0, sizeof(sock_in)); // reset sock_in to 0
init_server(&sock_in); // initialize server struct
assert(
bind(sockfd, (const struct sockaddr*)&sock_in, sizeof(sock_in)) >= 0 &&
"Port binding failed."
);
assert(
listen(sockfd, BACKLOG) == 0 &&
"Can't listen to the socket specified."
);
int bytes = 0;
char* chunk = memset(malloc(BUFFSIZE), 0, BUFFSIZE);
const int asocfd = accept(sockfd, NULL, 0);
assert(asocfd >= 0 && "Error in accepting socket."); // check if socket opened.
do {
bytes = recv(asocfd, chunk, BUFFSIZE - 1, 0);
memset(bytes == -1 ? chunk : chunk + bytes, 0, BUFFSIZE);
!errno ?
bytes && printf("%d\n%s\n", bytes, chunk)
: fprintf(stderr, "ERRNO: %d [%s]\n", errno, whaterror);
} while (errno == EAGAIN | bytes > 0);
return 0;
}
```