⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 listen_server.c

📁 sock编程 一个tcp源码一个udp源码 希望大家喜欢
💻 C
字号:
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>

#include "listen_server.h"

const int LISTEN_QUEUE=128;

int
listen_server(const char *hostname, 
              const char *service, 
              int         family,           
              int         socktype)
{
    struct addrinfo hints, *res, *ressave;
    int n, sockfd;
    
    memset(&hints, 0, sizeof(struct addrinfo));

    /*
       AI_PASSIVE flag: we use the resulting address to bind
       to a socket for accepting incoming connections. 
       So, when the hostname==NULL, getaddrinfo function will 
       return one entry per allowed protocol family containing 
       the unspecified address for that family.
    */

    hints.ai_flags    = AI_PASSIVE;
    hints.ai_family   = family;
    hints.ai_socktype = socktype; 
    
    n = getaddrinfo(hostname, service, &hints, &res);
    
    if (n <0) {
        fprintf(stderr, 
                "getaddrinfo error:: [%s]\n",  
                gai_strerror(n));
        return -1;
    }

    ressave=res;
   
    /* 
       Try open socket with each address getaddrinfo returned, 
       until we get a valid listening socket. 
    */
    sockfd=-1;
    while (res) {
        sockfd = socket(res->ai_family, 
                        res->ai_socktype, 
                        res->ai_protocol); 

        if (!(sockfd < 0)) {
            if (bind(sockfd, res->ai_addr, res->ai_addrlen) == 0) 
                break;

            close(sockfd);
            sockfd=-1;
        }
        res = res->ai_next;
    }
    
    if (sockfd < 0) {
        freeaddrinfo(ressave);
        fprintf(stderr,
                "socket error:: could not open socket\n");
        return -1;
    }

    listen(sockfd, LISTEN_QUEUE); 

    freeaddrinfo(ressave);

    return sockfd;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -