Skip to content

Instantly share code, notes, and snippets.

@haridas
Created April 27, 2014 13:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save haridas/11345081 to your computer and use it in GitHub Desktop.
Save haridas/11345081 to your computer and use it in GitHub Desktop.
TCP server with non blocking socket.
#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/wait.h>
#include <fcntl.h>
#define PORT "8000"
#define HOST "127.0.0.1"
#define MAX_LISTEN 5
void *get_in_addr(struct sockaddr *sa){
if(sa->sa_family == AF_INET){
return &(((struct sockaddr_in*)sa)->sin_addr);
}
return &(((struct sockaddr_in6*)sa)->sin6_addr);
}
int main(void){
int sd, new_sd;
int yes = 1;
int rv;
char s[INET6_ADDRSTRLEN];
struct addrinfo hints, *serverinfo, *p;
struct sockaddr_storage their_addr; // COnnectors address info.
socklen_t sin_size;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
if((rv = getaddrinfo(NULL, PORT, &hints, &serverinfo)) != 0){
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
// Loop through different results and pick up the first one.
for( p = serverinfo; p != NULL; p = p->ai_next){
if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
perror("server: socket");
continue;
}
if((fcntl(sd, F_SETFL, O_NONBLOCK)) < 0){
perror("error:fnctl");
exit(EXIT_FAILURE);
}
if(setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, &yes,
sizeof(int)) == -1){
perror("setsockopt");
exit(1);
}
if(bind(sd, p->ai_addr, p->ai_addrlen) == -1){
close(sd);
perror("server: bind");
continue;
}
break;
}
if (p == NULL){
fprintf(stderr, "server: failed to bind \n");
return 2;
}
freeaddrinfo(serverinfo); // No need for it further.
if(listen(sd, MAX_LISTEN) == -1){
perror("listen");
exit(1);
}
printf("server: waiting for connections...\n");
while(1){
sin_size = sizeof their_addr;
new_sd = accept(sd, (struct sockaddr *)&their_addr, &sin_size);
if(new_sd == -1){
perror("accept ...");
sleep(1);
continue;
}
inet_ntop(their_addr.ss_family,
get_in_addr((struct sockaddr *)&their_addr),
s, sizeof s);
printf("server: got connection from %s \n", s);
if(!fork()){ // This is child process.
close(sd); // Child doesn't need the listner socket. I'm not sure thought.
while(1){
int sent = send(new_sd, "Hello...", 8, 0);
if(sent == -1)
perror("send");
else
printf("Send packet");
}
close(new_sd);
exit(0);
}
close(new_sd); // Parent doesn't need child's socket.
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment