udp_connect函数

本文深入解析了使用C语言实现UDP连接的过程,通过示例代码详细介绍了如何利用getaddrinfo、socket、connect等函数进行UDP连接的创建。文章重点在于讲解UDP连接的底层实现机制,对于理解网络编程具有重要的参考价值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include    <netdb.h>
#include    <stdlib.h>
#include    <unistd.h>
#include    <string.h>
#include    <sys/socket.h>


int
udp_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_DGRAM;

    if ( (n = getaddrinfo(host, serv, &hints, &res)) != 0) {
        err_quit (
            "udp_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("udp_connect error for %s, %s", host, serv);
    }

    freeaddrinfo(ressave);

    return(sockfd);
}

 

转载于:https://www.cnblogs.com/soldierback/p/10744875.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值