Skip to content

Instantly share code, notes, and snippets.

@alurm
Created June 19, 2024 06:31
Show Gist options
  • Save alurm/9f9613b69785cda26ae9cef9584b9a60 to your computer and use it in GitHub Desktop.
Save alurm/9f9613b69785cda26ae9cef9584b9a60 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <sys/socket.h>
#include <netdb.h>
#include <fcntl.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
// For functions returning -1 and setting errno.
#define try(function, ...) ({ \
int result = function(__VA_ARGS__); \
if (result == -1) { perror(#function); exit(1); } \
result; \
})
int main(void) {
int s = try(socket, AF_INET, SOCK_STREAM, 0);
#ifdef main_reuse_address
try(setsockopt, s, SOL_SOCKET, SO_REUSEADDR, &(int) { 1 }, sizeof(int));
#endif
try(
bind,
s,
(struct sockaddr *)&(struct sockaddr_in) {
.sin_family = AF_INET,
.sin_port = htons(
#ifdef main_port
main_port
#else
8000
#endif
),
.sin_addr.s_addr = htonl((127 << 24) + 1),
},
sizeof(struct sockaddr_in)
);
try(listen, s, SOMAXCONN);
try(
accept,
s,
(struct sockaddr *)&(struct sockaddr_storage) { 0 },
&(socklen_t) { sizeof(struct sockaddr_storage) }
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment