Created
December 10, 2009 05:23
-
-
Save dmateos/253137 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <sys/socket.h> | |
#include <arpa/inet.h> | |
#include <sys/types.h> | |
#include <unistd.h> | |
#include <fcntl.h> | |
/* listening socket descriptor. */ | |
int _server_sock; | |
/* Holds descriptors to be read. */ | |
int _read_descrs[256]; | |
int _read_descrcount = 0; | |
int setup_socket() { | |
int lsock, csockinfosize; | |
struct sockaddr_in lsockaddr, csockinfo; | |
/* Clear/init some data. */ | |
memset(&lsockaddr, 0, sizeof(lsockaddr)); | |
memset(&csockinfo, 0, sizeof(csockinfo)); | |
csockinfosize = sizeof(csockinfo); | |
/* Setup our server socket to a listening state. */ | |
lsockaddr.sin_family = AF_INET; | |
lsockaddr.sin_addr.s_addr = htonl(INADDR_ANY); | |
lsockaddr.sin_port = htons(13373); | |
if((lsock = socket(AF_INET, SOCK_STREAM, 0)) < 0) | |
return -1; | |
if(bind(lsock, (struct sockaddr*)&lsockaddr, sizeof(lsockaddr)) < 0) | |
return -1; | |
if(listen(lsock, 1) < 0) | |
return -1; | |
/* Set as non blocking so we can select() the mother fucker. */ | |
fcntl(lsock, O_NONBLOCK); | |
/* Update global vars and add socket to read queue for accepts. */ | |
_server_sock = lsock; | |
_read_descrs[0] = _server_sock; | |
_read_descrcount++; | |
return 0; | |
} | |
int poll_io() { | |
int i; | |
fd_set read_list; | |
FD_ZERO(&read_list); | |
for(i = 0; i < _read_descrcount; i++) | |
FD_SET(_read_descrs[i], &read_list); | |
/* Do select then step thru list. */ | |
select(FD_SETSIZE, &read_list, NULL, NULL, NULL); | |
for(i = 0; i < _read_descrcount; i++) { | |
/* The server socket. */ | |
if(i == 0 && FD_ISSET(_read_descrs[i], &read_list)) { | |
int tmp = accept(_server_sock, NULL, 0); | |
printf("hi %d\n", i); | |
close(tmp); | |
} | |
else if(FD_ISSET(_read_descrs[i], &read_list)) { | |
printf("a client is ready %d\n", i); | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment