服务器客户端套接字:freeaddrinfo(3)放置

时间:2013-03-28 19:16:11

标签: c sockets free getaddrinfo

我必须在loopback接口上测试这个被动tcp服务器。 Ip和端口由命令行给出,并使用getopt进行解析。然后它使用getaddrinfo(3)设置并绑定TCP套接字并开始忙等待。

服务器:

#include "server_utils.h"
#define MAX_CONNECTION 10

#define EXIT_ON_ERROR_(s) { fprintf(stderr, s); exit(EXIT_FAILURE); } 

int access_permissions;
int session_status;
int sock_ds, acc_sock_ds;

int main(int argc, char** argv) {
    /*...*/

    int opt, errsv, client_addr_l;
    char *p_string;
    struct sockaddr_in client_addr;
    struct addrinfo hints;
    struct addrinfo *result, *rp;

    int check = 0;
    /*Parsing command line: port-number retrieving*/
    while (( opt = getopt(argc, argv, "p:")) != -1){
        check = 1;
        switch(opt){
            case 'p':
                /* String to unsigned long integer with ushort cast */
                p_string = optarg;
                strtoul(optarg, &optarg, 0); 
                if(*optarg)
                    EXIT_ON_ERROR_("String-integer conversion error\n");
                 break;
            default: /* '?' */
            fprintf(stderr, "Usage: %s -p port_number\n", argv[0]);
            exit(EXIT_FAILURE);
        }
    }
    if(!check){
        fprintf(stderr, "Usage: %s -p port_number\n", argv[0]);
        exit(EXIT_FAILURE);
    } 

    printf("Port number retrieved (%s), server is starting ...\n", p_string);
    memset(&hints, 0, sizeof(struct addrinfo));
    hints.ai_canonname = NULL;
    hints.ai_addr = NULL;
    hints.ai_next = NULL;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_family = AF_INET;
    hints.ai_flags = AI_PASSIVE|AI_NUMERICSERV;

    if(getaddrinfo(NULL, p_string, &hints, &result) != 0)
        /*freeaddrinfo(result); if get funct fails it should not be need*/
        EXIT_ON_ERROR_("Socket creation error!\n");

    for(rp = result; rp != NULL; rp = rp->ai_next){
        sock_ds = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
        if(sock_ds == -1) continue; //try next address

        /*A TCP server should usualy set SO_REUSEADDR option on its listening socket*/
        int optval = 1;                                     
            if( (setsockopt(sock_ds,SOL_SOCKET,SO_REUSEADDR,&optval,sizeof(optval))) == -1 ){
                EXIT_ON_ERROR_("Error on setsockopt call\n");
                freeaddrinfo(result); //???
            } 
        /*See TLPI Section 61.10*/

        if(bind(sock_ds, rp->ai_addr, rp->ai_addrlen) == 0)
            break; //success

        close(sock_ds); //failure, continue
    }
    if(rp == NULL) {
        freeaddrinfo(result); //?
        EXIT_ON_ERROR_("Could not bind socket\n");    
    }
    freeaddrinfo(result);        

    /*Server with passive socket*/
    if(listen(sock_ds, MAX_CONNECTION == -1)){
        fprintf(stderr, "Listen call error: %s\n", strerror(errno));
        exit(EXIT_FAILURE);
    }

    /*Initializing client_addr_l */
    client_addr_l = sizeof( struct sockaddr_in);
    printf("Server is ready. Waiting for client connections.\n"); 


    /*Busy-waiting server*/
    while(1){
    /*...*/
    }

每次服务器连接都成功。

客户端:

#include "client_utils.h"

#define EXIT_ON_ERROR_(s) { fprintf(stderr, s); exit(EXIT_FAILURE); } 


int main(int argc, char *argv[]) {

    int sock_ds, opt, check_p, check_a;
    char * ip, *port;
    struct addrinfo hints;
    struct addrinfo *result, *rp;

    check_p = 0; check_a = 0;
    /*port-number, ip address retrieval*/
    printf("Command line parsing: port-number, ip-address retrieving...\n");
    while ((opt = getopt(argc, argv, "a:p:")) != -1) {

        switch (opt) {
            case 'p':
                /* strtoul only used for string check */
                port = optarg;
                strtoul(optarg, &optarg, 0);
                if (*optarg) 
                    EXIT_ON_ERROR_("Invalid port number string submitted\n");

                check_p = 1;
                break;
           case 'a':
                ip = optarg;
                /*inet_aton only used for string check*/
                if(strcmp(ip, "localhost") != 0 && inet_aton(ip, NULL) == 0)
                    EXIT_ON_ERROR_("Invalid ip address string submitted\n");
                check_a = 1;
                break;
            default: /* '?' */
                fprintf(stderr, "Usage: %s -a ip_address ('localhost' for local server)"
                    " -p port_number\n", argv[0]);
                exit(EXIT_FAILURE);
        }
    }
    if (!check_p || !check_a) {
        fprintf(stderr, "Usage: %s -a ip_address ('localhost' for local server)"
            " -p port_number\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    printf("Command line parsed succesfully: <%s:%s>\n", ip, port);

    /*TCP Socket binding and connection*/
    memset(&hints, 0, sizeof(struct addrinfo));
    hints.ai_next = NULL;
    hints.ai_addr = NULL;
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_NUMERICSERV;

    if(getaddrinfo(ip, port, &hints, &result) != 0){
        /*getaddrinfo(resutl) ??? (same as sever)? */
        EXIT_ON_ERROR_("Socket creation error\n");
    }

    for(rp = result; rp != NULL; rp = rp->ai_next){
        sock_ds = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
        if(sock_ds == -1) 
            continue;

        if(connect(sock_ds, rp->ai_addr, rp->ai_addrlen) != -1)
             break;

        close(sock_ds);
    }

    if(rp == NULL){
       freeaddrinfo(result); //???
        EXIT_ON_ERROR_("Could not connect socket to any address\n");
    }
    freeaddrinfo(result);

    printf("Connection achieved with:%s on port:%s\n", ip, port);   
    /*...*/
}

我的疑问是关于freeaddrinfo(3)的功能。将它放置在完善的堆管理中是安全的吗?我把它放在套接字创建操作的最后,并在致命退出之前处于某种错误状态。我不确切知道如何以及什么获取操作malloc额外的空间。有人可以给我澄清一下吗?

1 个答案:

答案 0 :(得分:1)

你的一些freeaddrinfo(3)错误地放在之后对应EXIT_ON_ERROR_(),但除此之外我没有看到任何问题。

这个想法是getaddrinfo()构建了一个用于创建套接字的sockaddr结构的链接列表:一旦完成,你不再需要列表,所以freeaddrinfo()完全释放它 - 即,我不知道看到您的代码有任何问题。

我错过了你的任何问题吗?