Skip to content

Instantly share code, notes, and snippets.

@databoose
Created August 16, 2020 12:43
Show Gist options
  • Save databoose/0104a91e19e3efeea8288100b1d7ae40 to your computer and use it in GitHub Desktop.
Save databoose/0104a91e19e3efeea8288100b1d7ae40 to your computer and use it in GitHub Desktop.
snippet
int main() {
thread_logger *thl = new_thread_logger(debug_mode);
thread_store(create);
self_pid = getpid();
sprintf(appendcmd, "ps hH p %d | wc -l > /dev/shm/linkup-varstore/thread_count", self_pid);
servsockfd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in serv_addr;
struct sockaddr_in cli_addr;
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(64912);
serv_addr.sin_addr.s_addr = inet_addr("10.0.0.224");
memset(&cli_addr, 0, sizeof(struct sockaddr_in)); //initializing cli_addr struct
if (setsockopt(servsockfd, SOL_SOCKET, SO_REUSEADDR, &(int){1}, sizeof(int)) < 0) {
LOGF_ERROR(thl, 0, "setsockopt so_reuseaddr unsuccessful : %s (Error code %d)\n", strerror(errno), errno);
errno = 0;
}
LOGF_DEBUG(thl, 0, "Set reuse", NULL);
LOGF_DEBUG(thl, 0, "Binding...", NULL);
int bind_status;
bind_status = bind(servsockfd, (SA*)&serv_addr, sizeof(serv_addr));
if (bind_status == -1) {
LOGF_ERROR(thl, 0, "Bind unsuccessful : %s (Error code %d)", strerror(errno), errno);
errno = 0;
if (errno == 98) {
LOGF_ERROR(thl, 0, "More than one process running maybe?", NULL);
exit(0);
}
}
int listen_status;
LOGF_INFO(thl, 0, "Listening...", NULL);
listen_status = listen(servsockfd, SERVER_BACKLOG); // second param is backlog, aka how many connections can wait in one point in time
if (listen_status == -1) {
LOGF_ERROR(thl, 0, "Listen unsuccessful : %s (Error code %d)\n", strerror(errno), errno);
errno = 0;
}
// user now has input
pthread_t input_thread;
pthread_create(&input_thread, NULL, (void *)cmd_input, NULL);
for (;;) {
usleep(SERVER_TICKRATE);
int clisock;
socklen_t cli_addr_size = sizeof(cli_addr);
clisock = accept(servsockfd, (SA*)&cli_addr, &cli_addr_size); // last two parameters should fill an optionable client struct for info
if (clisock >= 0) {
printf("\n");
if (strcmp(inet_ntoa(cli_addr.sin_addr), ipaddr) == 0) { //if banned ip matches ipaddr string
LOGF_INFO(thl,0, "Banned IP address %s attempted to connect, refusing to open connection thread", inet_ntoa(cli_addr.sin_addr));
break;
}
LOGF_INFO(thl, 0, "Connection accepted from : %s:%d", inet_ntoa(cli_addr.sin_addr), ntohs(cli_addr.sin_port));
pthread_t sckthread;
int *pclient = malloc(sizeof(int));
*pclient = clisock;
pthread_create(&sckthread, NULL, (void *)handle_connection, pclient);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment