비저항 socket 하위 클라이언트connect + select 간단 데모

5725 단어 필기
간단하게 비저항 socket을 실현하고 시간 초과 응답을 하며 연결 성공 여부를 판단합니다.
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#define IPADDR "www.baidu.com"
#define PORT 80

int main()
{
  struct addrinfo *res, hint;
    fd_set rest, west;
  int error;
  socklen_t optlen = sizeof(error);
    memset(&hint, 0, sizeof(hint));
    hint.ai_family = AF_INET;
    hint.ai_socktype = SOCK_STREAM;
    if (0 != getaddrinfo(IPADDR, NULL, &hint, &res)) {
        goto err0;
    }

    int sock = socket(res->ai_family, res->ai_socktype, 0);
    if (-1 == sock)
        goto err1;
    if(-1 == fcntl(sock, F_SETFL, fcntl(sock, F_GETFL) | O_NONBLOCK))
        goto err2;

    struct sockaddr_in addr;

    memset(&addr, 0 , sizeof(addr));
  addr.sin_family = res->ai_family;
  addr.sin_port = htons(PORT);
  addr.sin_addr.s_addr = ((struct sockaddr_in *)(res->ai_addr))->sin_addr.s_addr;

  int ret = connect(sock, (struct sockaddr *)&addr, sizeof(addr));
    printf("ret = %d,errno = %d
"
,ret,errno); if (-1 == ret && EINPROGRESS != errno) goto err2; /* select */ FD_ZERO(&rest); FD_ZERO(&west); FD_SET(sock, &rest); FD_SET(sock, &west); struct timeval tempval; tempval.tv_sec = 3; tempval.tv_usec = 0; int flag = select(sock+1, &rest, &west, NULL, &tempval);// if(flag < 0) { printf("select error
"
); goto err2; } else { /* */ /* , : , : , getsockopt sock , 0 0 。 */ if(!FD_ISSET(sock, &rest) && !FD_ISSET(sock, &west)) { printf("connect no response
"
); goto err2; } else if(FD_ISSET(sock, &rest) && FD_ISSET(sock, &west)) { flag = getsockopt(sock, SOL_SOCKET, SO_ERROR, &error, &optlen); if(flag == 0 && error == 0) { printf("connect success....
"
); } else { printf("connect error....
"
); goto err2; } } else if(!FD_ISSET(sock, &rest) && FD_ISSET(sock, &west)) { printf("connect success....
"
); } else { printf("connect error....
"
); goto err2; } } close(sock); freeaddrinfo(res); return 0; err2: close(sock); err1: freeaddrinfo(res); err0: return 0; }

좋은 웹페이지 즐겨찾기