ITeye博客

防止connect阻塞之select方法

kingoal · 2009-05-18 23:17 · Networking · Socket · F# · Markdown

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

#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>

int main(int argc,char* argv[])
{
	int status;
	struct addrinfo *addr;
	struct addrinfo hints;
	int sockfd;

	if(argc<2)
	{
		printf("myconn <host>\n");
		exit(-1);
	}

	memset(&hints,0,sizeof(struct addrinfo));
	hints.ai_family=AF_INET;
	hints.ai_socktype=SOCK_STREAM;
	hints.ai_flags = AI_PASSIVE;

	if((status=getaddrinfo(argv[1],"80",&hints,&addr))!=0)
	{
		fprintf(stderr,"getaddrinfo: %s\n", gai_strerror(status));
		exit(-1);
	}

	sockfd = socket(addr->ai_family,addr->ai_socktype,addr->ai_protocol);
	if(sockfd==-1)
	{
		perror("socket");
		exit(-1);
	}

	//Nonblock the socket
	int flags = fcntl(sockfd,F_GETFL,0);
	fcntl(sockfd,F_SETFL,flags|O_NONBLOCK);

	int start = time(NULL);
	status = connect(sockfd, addr->ai_addr,addr->ai_addrlen);
	if(errno!=EINPROGRESS)
	{
		printf("status: %d\n",status);
		perror("connect");
	}

	fd_set wset;
	FD_ZERO(&wset);
	FD_SET(sockfd,&wset);
	int maxfd = sockfd+1;
	struct timeval timeout;
	timeout.tv_sec = 5;
	timeout.tv_usec = 0;
	status = select(maxfd, NULL,&wset, NULL,&timeout);
	if(status == -1)
	{
		perror("select");
	}

	if(FD_ISSET(sockfd,&wset))
	{
		int error;
		int len = sizeof(error);

		status = getsockopt(sockfd,SOL_SOCKET,SO_ERROR,&error,&len);
		if(status<0||error!=0)
			perror("getsockopt");
	}

	int end = time(NULL);

	printf("Connect to %s: Time: %d seconds\n", argv[1],end-start);

	close(sockfd);

	freeaddrinfo(addr);
	return 0;
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。