Skip to content

Instantly share code, notes, and snippets.

@PeterWaIIace
Created July 9, 2020 21:43
Show Gist options
  • Save PeterWaIIace/a14c629a153fe4e5c7b828dc5e1dc585 to your computer and use it in GitHub Desktop.
Save PeterWaIIace/a14c629a153fe4e5c7b828dc5e1dc585 to your computer and use it in GitHub Desktop.
TCP listening non-blocking socket server template.
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/ioctl.h>
#include <netdb.h>
#include <netinet/in.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <time.h>
#define PORT 8080
#define BUFF_SIZE 4096
#define SOCK_ADDR struct sockaddr
int main(int argc, char **argv){
clock_t start, end;
int sockfd, n,errcode,new_socket,opt=1;
int sendbytes;
struct sockaddr_in servaddr;
struct sockaddr_in destaddr;
char sendline[BUFF_SIZE];
char readline[BUFF_SIZE];
// usage check
// if(argc != 2)
// return 0;
sockfd = socket(AF_INET,SOCK_STREAM,0);
// socket preparation
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(PORT);
servaddr.sin_addr.s_addr = INADDR_ANY;
if(0 > (errcode = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR ,
&opt, sizeof(opt)))){
perror("setsockopt");
exit(EXIT_FAILURE); // 0 - success, -1 - fail
}
if(0 > (errcode = bind(sockfd,&servaddr,sizeof(servaddr)))){
perror("bind");
exit(EXIT_FAILURE);
}
if(0 > (errcode = listen(sockfd,4))){
perror("listen");
exit(EXIT_FAILURE);
}
socklen_t cli_addr_size = sizeof(servaddr);
if (0 > (new_socket = accept(sockfd, &destaddr,&cli_addr_size)))
{
printf("new_socket: %d",new_socket);
perror("accept");
exit(EXIT_FAILURE);
}
printf("Connection from: %s \n",inet_ntoa(destaddr.sin_addr));
int flags = fcntl(sockfd,F_GETFL,0);
if(0 > (flags)){
perror("flags");
exit(EXIT_FAILURE); // 0 - success, -1 - fail
}
// assert(flags != -1);
fcntl(sockfd, F_SETFL, flags | O_NONBLOCK);
while(new_socket > 0){
n = read(new_socket , readline, BUFF_SIZE);
printf("%s\n",readline);
close(new_socket);
new_socket = accept(sockfd, &destaddr,&cli_addr_size);
}
printf("Connection closed: %s \n",inet_ntoa(destaddr.sin_addr));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment