其他分享
首页 > 其他分享> > udp_server函数

udp_server函数

作者:互联网

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

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

    bzero(&hints, sizeof(struct addrinfo));
    hints.ai_flags = AI_PASSIVE;
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_DGRAM;

    if ( (n = getaddrinfo(host, serv, &hints, &res)) != 0) {
        err_quit (
            "udp_server 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;        /* error - try next one */
        }

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

        close(sockfd);        /* bind error - close and try next one */
    } while ( (res = res->ai_next) != NULL);

    if (res == NULL) {        /* errno from final socket() or bind() */
        err_sys("udp_server error for %s, %s", host, serv);
    }

    if (addrlenp) {
        *addrlenp = res->ai_addrlen;    /* return size of protocol address */
    }

    freeaddrinfo(ressave);

    return(sockfd);
}

 

标签:udp,函数,ai,res,server,sockfd,include,hints
来源: https://www.cnblogs.com/soldierback/p/10744877.html