Skip to content

Instantly share code, notes, and snippets.

@znnahiyan
Last active August 30, 2017 17:24
Show Gist options
  • Save znnahiyan/5953089 to your computer and use it in GitHub Desktop.
Save znnahiyan/5953089 to your computer and use it in GitHub Desktop.
Minimal example code for opening a TCP socket, listening for connections, and outputing incoming data to stdout. Two versions: (a) No error checking, and (b) error checking with macros.
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#define LISTEN_PORT (1234)
#define ASSERT_FATAL(condition, function) \
do { \
if ((condition)) { \
perror((function)); \
fputs("__FILE__:__LINE__: fatal: error from " function "(), exiting...\n", stderr); \
return 1; \
} \
} while (0)
int main()
{
int listen_fd, connection_fd;
struct sockaddr_in address;
char recvbuff[65536];
int recvlen;
int status;
address.sin_family = AF_INET;
address.sin_port = htons(LISTEN_PORT);
address.sin_addr.s_addr = INADDR_ANY;
listen_fd = socket(AF_INET, SOCK_STREAM, 0); ASSERT_FATAL(listen_fd == -1, "socket");
status = bind(listen_fd, (const struct sockaddr*) &address, sizeof(struct sockaddr_in)); ASSERT_FATAL(status == -1, "bind");
status = listen(listen_fd, 1); ASSERT_FATAL(status == -1, "listen");
// @note: accept() is a blocking function by default.
connection_fd = accept(listen_fd, NULL, NULL); ASSERT_FATAL(connection_fd == -1, "accept");
while (1)
{
// @note: recv() is a blocking function by default.
// @returns: 0 on connection closure, -1 on failure.
recvlen = recv(connection_fd, recvbuff, sizeof(recvbuff), 0);
if (recvlen <= 0)
{
if (recvlen == -1)
perror("recv");
break;
}
fwrite(recvbuff, sizeof(char), recvlen, stdout);
}
return 0;
}
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#define LISTEN_PORT (1234)
int main()
{
int listen_fd, connection_fd;
struct sockaddr_in address;
char recvbuff[65536];
int recvlen;
address.sin_family = AF_INET;
address.sin_port = htons(LISTEN_PORT);
address.sin_addr.s_addr = INADDR_ANY;
listen_fd = socket(AF_INET, SOCK_STREAM, 0);
bind(listen_fd, (const struct sockaddr*) &address, sizeof(struct sockaddr_in));
listen(listen_fd, 1);
// @note: accept() is a blocking function by default.
connection_fd = accept(listen_fd, NULL, NULL);
while (1)
{
// @note: recv() is a blocking function by default.
// @returns: 0 on connection closure, -1 on failure.
recvlen = recv(connection_fd, recvbuff, sizeof(recvbuff), 0);
if (recvlen <= 0)
break;
fwrite(recvbuff, sizeof(char), recvlen, stdout);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment