您的位置:首页 > 运维架构 > Linux

linux非阻塞connect(续)

2012-01-10 15:50 232 查看
加入Epoll监听后的代码:

#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>

#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>

#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <cstdlib>

#include <openssl/ssl.h>
#include <openssl/err.h>
#include <sys/epoll.h>

#define READ
#define WRITE

#define OUT(str) do{cout<<str<<endl;}while(0)
#define TEST do{printf("line:%d\n",__LINE__);}while(0)

using namespace std;

static int EpollCreate(){

int epfd;

epfd = epoll_create(1024);

if(epfd== -1){
return -1;
}else{
return epfd;
}
}

static bool EpollAdd(int epfd,int *fd){

struct epoll_event ev;
int ret;

ev.events = EPOLLIN | EPOLLOUT;
ev.data.ptr=fd;

ret=epoll_ctl(epfd, EPOLL_CTL_ADD, *fd, &ev);
if(ret==-1){
return false;
}

return true;
}

static bool EpollDel(int epfd, int fd){

struct epoll_event ev;
int ret;

ev.data.ptr=NULL;
ret=epoll_ctl(epfd, EPOLL_CTL_DEL, fd, &ev);
if(ret==-1){
return false;
}

return true;
}

static void Check(int fd){

int ret,error=1;
socklen_t len;
len=sizeof(error);
ret=getsockopt(fd,SOL_SOCKET,SO_ERROR,&error,&len);
if(error == 0){
OUT("SUCESS");
}else{
OUT("FAILED");
}
return;

}
static void EpollRun(int epfd,int timeout){

const int nevents = 1024;
struct epoll_event evs[nevents];
int *fd;
int n = epoll_wait(epfd, evs, nevents, timeout);
for(int i=0;i<n;i++){

fd=(int *)evs[i].data.ptr;

if(evs[i].events & EPOLLIN){

#ifdef READ
OUT("Read event note!");
OUT(*fd);
Check(*fd);
OUT("\n\n");
#endif

}
if(evs[i].events & EPOLLOUT){

#ifdef WRITE
OUT("Write event note!");
OUT(*fd);
Check(*fd);
OUT("\n\n");
#endif

}
}
}

static int CreateScok(const char * ip){

struct sockaddr_in serv_addr;
serv_addr.sin_family=AF_INET;
serv_addr.sin_port=htons(443);
serv_addr.sin_addr.s_addr=inet_addr(ip);
bzero(&(serv_addr.sin_zero),8);

SSL_CTX *ctx;
SSL *ssl;

SSL_library_init();
OpenSSL_add_all_algorithms();
SSL_load_error_strings();
ctx= SSL_CTX_new(SSLv23_client_method());
if(ctx == NULL) {
return -1;
}

int sockfd;
if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1){

OUT("socket create error");

return -1;
}

int flags=fcntl(sockfd,F_GETFL,0);
fcntl(sockfd,F_SETFL,flags|O_NONBLOCK);

int n=connect(sockfd,(struct sockaddr *)&serv_addr, sizeof(struct sockaddr));
sleep(2);

if(n<0){

if(errno !=EINPROGRESS){
perror(strerror(errno));
return -1;
}else{
OUT(ip);
OUT("EINPROGRESS");
}
}else{
OUT(ip);
}

ssl= SSL_new(ctx);
if(SSL_set_fd(ssl, sockfd) == 0){
return -1;
}
SSL_set_connect_state(ssl);

if(n==0){

OUT("connect sucess immediately");
return sockfd;
}

return sockfd;

}

int main(){

ifstream ipin("./iplist.txt");

string line;

int epfd=EpollCreate();

while(getline(ipin,line)){

int sock=CreateScok(line.c_str());

if(sock==-1){

OUT("connect error");
return 0;

}else{

EpollAdd(epfd,&sock);

}

EpollRun(epfd,100);
//close(sock);
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息