码迷,mamicode.com
首页 > 其他好文 > 详细

tcp_connect函数

时间:2019-04-21 14:37:16      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:clu   connect   size   sock   nts   nec   save   get   def   

#include    <netdb.h>
#include    <stddef.h>
#include    <unistd.h>
#include    <strings.h>
#include    <sys/socket.h>

int
tcp_connect(const char *host, const char *serv)
{
    int                sockfd, n;
    struct addrinfo    hints, *res, *ressave;

    bzero(&hints, sizeof(struct addrinfo));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;

    if ( (n = getaddrinfo(host, serv, &hints, &res)) != 0) {
        err_quit( "tcp_connect error for %s, %s: %s",
                   host, serv, gai_strerror(n)
        );
    }
    ressave = res;

    do {
        sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
        if (sockfd < 0) {
            continue;    /* ignore this one */
        }

        if (connect(sockfd, res->ai_addr, res->ai_addrlen) == 0) {
            break;        /* success */
        }

        close(sockfd);    /* ignore this one */
    } while ( (res = res->ai_next) != NULL);

    if (res == NULL) {    /* errno set from final connect() */
        err_sys("tcp_connect error for %s, %s", host, serv);
    }

    freeaddrinfo(ressave);

    return(sockfd);
}

 

tcp_connect函数

标签:clu   connect   size   sock   nts   nec   save   get   def   

原文地址:https://www.cnblogs.com/soldierback/p/10744886.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!