非阻塞式connect的Linux实现

下面内容摘自是connect的man手册,程序根据这段内容完成。
   EINPROGRESS
              The socket is non-blocking and the connection cannot be completed immediately.   It  is  possible  to  select(2)  or
              poll(2)  for  completion  by  selecting the socket for writing.  After select(2) indicates writability, use getsock-
              opt(2) to read the SO_ERROR option at  level  SOL_SOCKET  to  determine  whether  connect()  completed  successfully
              (SO_ERROR  is  zero)  or unsuccessfully (SO_ERROR is one of the usual error codes listed here, explaining the reason
              for the failure).

#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <stdio.h>
#include <sys/time.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <strings.h>
#include <stdlib.h>
int  main()
{
    int sockfd;
    sockfd = socket(AF_INET,SOCK_STREAM,0);
    
    int flags;
    flags = fcntl(sockfd,F_GETFD,0);
    flags |= O_NONBLOCK;
    fcntl(sockfd,F_SETFD,flags);
    
    struct sockaddr_in addr;
    bzero(&addr,sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(49152);
    inet_pton(AF_INET,"192.168.1.1",&addr.sin_addr.s_addr);
    
    fd_set writefds;
    FD_ZERO(&writefds);
    FD_SET(sockfd,&writefds);
    struct timeval timeout;
    timeout.tv_sec = 5;
    timeout.tv_usec = 0;
   
   iResult = connect(sockfd,(struct sockaddr *)&addr,sizeof(addr));
    if(iResult == 0){
        printf("connect imidiataly\n");
        goto done;
    }
    iResult = select(testfd+1,NULL,&writefds,NULL,&timeout);
    if(0 == iResult){
        printf("timeout!\n");
        goto done;
    }
    if(-1 == iResult){
        perror("select error:");
        goto done;
    }
    if(FD_ISSET(sockfd,&writefds)){
        int error;
        socklen_t errorlen = sizeof(error);
        getsockopt(sockfd,SOL_SOCKET,SO_ERROR,&error,&errorlen);
   }

done:
   if(error){
       errno = error;
       perror("SO_ERROR");
       close(sockfd);
   }

    flags = fcntl(sockfd,F_GETFD,0);
    flags &= ~O_NONBLOCK;
    fcntl(sockfd,F_SETFD,flags);
    return 0;
}    


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值