Skip to content

Instantly share code, notes, and snippets.

@eisenwinter
Created May 12, 2018 09:02
Show Gist options
  • Select an option

  • Save eisenwinter/22f2107b5c703305967f8a5defc8ce7c to your computer and use it in GitHub Desktop.

Select an option

Save eisenwinter/22f2107b5c703305967f8a5defc8ce7c to your computer and use it in GitHub Desktop.
NEP Ue2
#include<sys/types.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<sys/socket.h>
#include<netdb.h>
extern void server_process(int);
void main (int argc, char *argv[]){
struct addrinfo hints;
struct addrinfo *results, *rp;
struct sockaddr_storage peer_addr;
int peer_addr_len;
memset(&hints, 0, sizeof(hints));
int ret_val, main_sock, client_sock;
if(argc != 2){
fprintf(stderr, "Usage: u2 <port>\n");
exit(EXIT_FAILURE);
}
hints.ai_family = AF_UNSPEC; //AFINET = ipv4, AFINET6 = ipv6
hints.ai_socktype = SOCK_STREAM; // SOCK_STREAM = tcp, SOCK_DGRAM = udp
hints.ai_flags = AI_PASSIVE; //passive open = server
ret_val = getaddrinfo(NULL, argv[1], &hints, &results);
for(rp = results; rp != NULL; rp = rp->ai_next){
main_sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if(main_sock < 0){
continue;
}
if(bind(main_sock, rp->ai_addr, rp->ai_addrlen) == 0){
//bind successful
break;
}else{
close(main_sock);
}
}
freeaddrinfo(results);
if(rp == NULL){
// no configuration was successfully
perror("bind");
exit(EXIT_FAILURE);
}
if(listen(main_sock, 10)){
perror("listen");
exit(EXIT_FAILURE);
}
for(;;){
peer_addr_len = sizeof(peer_addr);
client_sock = accept(main_sock,(struct sockaddr*)&peer_addr,&peer_addr_len);
if(client_sock < 0){
perror("accept");
exit(EXIT_FAILURE);
}
server_process(client_sock);
close(client_sock);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment