00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027 #include <string.h>
00028 #include <unistd.h>
00029 #include <cstdio>
00030 #include <errno.h>
00031
00032 #include "poller_util.h"
00033 #include "poller.h"
00034
00035 namespace fpoller{
00036
00037 int callback_wrapper::operator()(int fd){
00038 if (cb_.ptr()) {
00039 return cb_->operator()(fd);
00040 } else {
00041 return REMOVE;
00042 }
00043 }
00044
00045 int get_listen_socket(int port, int backlog){
00046 int sock;
00047 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){
00048 throw exception("could not create listen socket",errno);
00049 }
00050 sockaddr_in sa;
00051
00052 memset(&sa,0,sizeof(sockaddr_in));
00053
00054 sa.sin_family = AF_INET;
00055
00056
00057
00058
00059
00060 #if defined __OPTIMIZE__ && defined __i386__ && defined __linux__
00061 sa.sin_port = ((((port) >> 8) & 0xff) | (((port) & 0xff) << 8));
00062 #else
00063 sa.sin_port = htons(port);
00064 #endif
00065 sa.sin_addr.s_addr = htonl(INADDR_ANY);
00066
00067
00068 int one=1;
00069 if (setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&one,sizeof(int)) != 0){
00070 throw exception("could not set socket to be reusable",errno);
00071 }
00072 if (bind(sock,(struct sockaddr *)&sa, sizeof(sa)) < 0) {
00073 throw exception("could not bind listen socket",errno);
00074 }
00075 if (listen(sock,backlog) < 0) {
00076 throw exception("could not start listen socket listening",errno);
00077 }
00078 return sock;
00079 }
00080
00081 void set_non_blocking(int fd){
00082 int flags = fcntl(fd,F_GETFL,0);
00083 if (flags<0) {
00084 throw exception("could not get socket's flags to set it non-blocking",errno);
00085 }
00086 if (fcntl(fd,F_SETFL,flags | O_NONBLOCK) <0){
00087 throw exception("could not set socket non-blocking",errno);
00088 }
00089 }
00090
00091 }
00092
00093
00094