转:getaddrinfo函数详解

转自:http://blog.csdn.net/andyxie407/article/details/1672325

有这样一个C/S程序,server提供一个叫做ruptime的服务,功能是当有客户端连接时调用uptime程序,并将结果发送到client。可是现在的问题是,这个服务系统本来是没有的,所以调用getaddrinfo的时候会返回如下错误:

Servname not supported for ai_socktype

我觉得可能是需要编辑/etc/service文件把自己这个服务加进去,可是我加了之后没管用(设的端口是4000),开机的时候提示启动服务失败,所以我的问题就是如何开启我这个服务器程序提供的服务

个人认为,这个问题就是对getaddrinfo函数的应用和理解,下面帖子的内容基本上是对Advanced Programming in linux Environment这本书里的16-6等几个程序的解释,刚开始对getaddrinfo这个函数和编辑/etc/service等不了解,所会有以上的问题存在。下面是资料。

bumpy:~/tmp$ gcc a.c
bumpy:~/tmp$ ./a.out <==== 没有改/etc/services 前
getaddrinfo error: Servname not supported for ai_socktype
bumpy:~/tmp$ vi a.c
bumpy:~/tmp$ sudo vi /etc/services <==== 添加ruptimed 4000/tcp到合适的位置(4000可以改成任何一个没有用过的端口号)
bumpy:~/tmp$ ./a.out
OK

真是惭愧啊,本来是问问题的,竟然加精了,其实功劳多半是算roamingo兄弟的,我本来想在程序版再发一篇关于如何使用getsockaddr这个函 数的,不过既然这样,我就在这里写吧,如果版主觉得不合适,也可以转到程序版,下面的代码是基于apue第十六章并自己加以修改,以前我以前都是在 windows下开发的网络程序,而且中间隔了很长时间,而linux下的c编程又刚接触不久,所以有什么地方理解不到位,希望兄弟们指正。

getsockaddr这个函数的功能是将主机名映射成主机的地址,是个新的接口,以取代以 前的gethostbyname这个函数,因为后者不能处理ipv6的地址,并且以被标记为废弃,关于参数的细节有兴趣的朋友可以查帮助,我这里主要说一 下应该注意的问题,在使用中,最重要的是hint.ai_flags这个参数的设定问题,服务器端和客户端都分成两种情况,先说服务器端

1.服务器端以服务的形式提供给用户,相关的代码在3楼,下面的代码是用到的库函数

#include <sys/socket.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <errno.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <fcntl.h>
#include <syslog.h>

#define MAXSLEEP 128

int
connect_retry(int sockfd, const struct sockaddr *addr, socklen_t alen)
{
    int nsec;

    for (nsec = 1; nsec <= MAXSLEEP; nsec <<= 1) {
    if (connect(sockfd, addr, alen) == 0)
    return(0);
    if (nsec <= MAXSLEEP/2)
    sleep(nsec);
    }
    return(-1);
}

int
initserver(int type, const struct sockaddr *addr, socklen_t alen, int qlen)
{
    int fd;
    int err = 0;
    int reuse = 1;

    if ((fd = socket(addr->sa_family, type, 0)) < 0)
        return(-1);
    if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(int)) < 0) {
        err = errno;
        goto errout;
    }
    if (bind(fd, addr, alen) < 0) {
        err = errno;
        goto errout;
    }
    if ((type == SOCK_STREAM) || (type == SOCK_SEQPACKET)) {
        if (listen(fd, qlen) < 0) {
            err = errno;
            goto errout;
        }
    }
    return(fd);
errout:
    close(fd);
    errno = err;
    return(-1);
}

void
daemonize(const char *cmd)
{
    int i, fd0, fd1, fd2;
    pid_t pid;
    struct rlimit rl;
    struct sigaction sa;

    umask(0);

    if (getrlimit(RLIMIT_NOFILE, &rl) < 0) {
        printf("getrlimit failed");
        exit(1);
    }

    if ((pid = fork()) < 0) {
        printf("first fork failed");
        exit(1);
    }
    else if (pid > 0) {
        exit(0);
    }

    setsid();

    sa.sa_handler = SIG_IGN;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;
    if (sigaction(SIGHUP, &sa, NULL) < 0) {
        printf("sigaction failed");
        exit(1);
    }
    if ((pid = fork()) < 0) {
        printf("second fork failed");
        exit(1);
    }
    else if (pid > 0) {
        exit(0);
    }

    if (chdir("/") < 0) {
        printf("chdir failed");
        exit(1);
    }

    if (rl.rlim_max == RLIM_INFINITY)
        rl.rlim_max = 1024;
    for (i = 0; i < rl.rlim_max; i++)
        close(i);

    fd0 = open("/dev/null", O_RDWR);
    fd1 = dup(0);
    fd2 = dup(0);

    openlog(cmd, LOG_CONS, LOG_DAEMON);
    if (fd0 != 0 || fd1 != 1 || fd2 != 2) {
        syslog(LOG_ERR, "unexpected file descriptor %d %d %d", fd0, fd1, fd2);
        exit(1);
    }
}

首先说说什么是服务,端口号大家都知道,比如smtp这个就是服务,而它使用的端口号是 25,但是系统怎么知道它需要使用端口25呢,就是通过在/etc/services这个文件里进行登记,打开它你会发现里面登记了几乎所有的像 ftp,dns这样的公开的服务,同样的道理,如果我们要使用自己的服务,也需要在里面登记,但要注意端口号不能小于1024,并且不能和已登记的重复, 还有一点是关于服务名,这个名字没有必要和程序名一样,比如上面的代码,程序名是ruptimed,而服务名是ruptime, 只要你认为能代表程序的功能就行。现在大家应该知道了什么是服务了,就是程序的代号。现在再回到getaddrinfo这个函数,当我将第二个参数设为服 务名(ruptime)时,返回的结果里的端口号就是在/etc/services里登记的端口号,有人会说了,那第一个参数呢?是这样的,大家可以打开 /etc/hosts这个文件,在开头有几行主机名和地址的列表,下面是我的hosts文件的内容:

127.0.0.1 localhost
192.168.1.104 wawxdyy

# The following lines are desirable for IPv6 capable hosts
::1 ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts

如果我将第一个参数设为localhost,那么返回的地址就是127.0.0.1,如果设为wawxdyy,返回的就是192.168.1.104。
如果要想以服务的形式运行服务器程序,这两个参数一定要明确指定,并且主机名不能是localhost,只有这样返回的结果才是有效的,才能用于后面的绑定。
2 服务器程序用端口号的形式发布: 这种情况下就没有必要在/etc/services里登记了,但是hint结构的ai_flags的参数设定有注意的地方,在上面的那种情况,因为主机名 和服务名都明确提供了,所以即使ai_flags设为0也能返回正确的结果,但是现在我们将第二个参数设为端口号,这样的话,我们必须将hint结构的 ai_flags设为AI_PASSIVE,这样返回的结果才能用于后面的监听绑定,否则不能,因为AI_PASSIVE就是告诉getaddrinfo返回的地址是用于监听绑定的。下面是相关的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <syslog.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <fcntl.h>

#ifndef HOST_NAME_MAX
#define HOST_NAME_MAX 64
#endif

#define BUFLEN 128
#define QLEN 10

extern int initserver(int, const struct sockaddr *, socklen_t, int);
extern void daemonize(const char *);

void
serve(int sockfd)
{
    int clfd, status;
    pid_t pid;

    for (;;) {
    if ((clfd = accept(sockfd, NULL, NULL)) < 0) {
        syslog(LOG_ERR, "accept error: %m/n");
        exit(-1);
    }

    if ((pid = fork()) < 0) {
        syslog(LOG_ERR, "fork error: %m/n");
        exit(-1);
    }
    else if (pid == 0) {
        if (dup2(clfd, STDOUT_FILENO) != STDOUT_FILENO ||
            dup2(clfd, STDERR_FILENO) != STDERR_FILENO) {
            syslog(LOG_ERR, "dup2 error: %m/n");
            exit(-1);
        }
        close(clfd);
        execl("/usr/bin/uptime", "uptime", (char *)0);
        syslog(LOG_ERR, "unexpected return from execl: %m");
        }
        else {
            close(clfd);
            waitpid(pid, &status, 0);
        }
    }
}

int
main(void)
{
    struct addrinfo *ailist, *aip;
    struct addrinfo hint;
    struct sockaddr_in *sinp;
    int sockfd;
    int err, n;
    char *host;
    char buf[INET_ADDRSTRLEN];

#ifdef _SC_HOST_NAME_MAX
    n = sysconf(_SC_HOST_NAME_MAX);
    if (n < 0)
#endif
    n = HOST_NAME_MAX;

    if ((host = malloc(n)) == NULL) {
        printf("malloc error: %s/n", strerror(errno));
        exit(-1);
    }
    if (gethostname(host, n) < 0) {
        printf("gethostname error: %s/n", strerror(errno));
        exit(-1);
    }
    syslog(LOG_ERR, "hostname is %s", host);
    daemonize("ruptimed");

    hint.ai_flags = AI_PASSIVE;
    hint.ai_family = 0;
    hint.ai_socktype = SOCK_STREAM;
    hint.ai_protocol = 0;
    hint.ai_addrlen = 0;
    hint.ai_addr = NULL;
    hint.ai_canonname = NULL;
    hint.ai_next = NULL;
    if ((err = getaddrinfo(NULL, "2000", &hint, &ailist)) != 0) {
        syslog(LOG_ERR, "getaddrinfo error: %s", gai_strerror(err));
        exit(-1);
    }
    for (aip = ailist; aip != NULL; aip = aip->ai_next) {
        sinp = (struct sockaddr_in *)aip->ai_addr;
        short port = ntohs(sinp->sin_port);
        syslog(LOG_ERR, "port is %d/n", port);
        if (inet_ntop(aip->ai_family, &sinp->sin_addr, buf, INET_ADDRSTRLEN) != NULL)
            syslog(LOG_ERR, "addr is %s/n", buf);
        if ((sockfd = initserver(aip->ai_socktype, aip->ai_addr,
             aip->ai_addrlen, QLEN)) >= 0) {
            serve(sockfd);
            exit(0);
        }
    }
    exit(-1);
}

再来说说客户端:相似地也有两种情况:
1 以服务的方式连接服务器:如果用户只知道服务器提供的服务,而不知道其端口号,就用这种方式,并且我们也需要在/etc/services里登记,否则也 会出现“Servname not supported for ai_socktype”这样的错误,但是端口号不必于服务器端一样,下面是代码:

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <netdb.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#define BUFLEN 128

extern connect_retry(int sockfd, const struct sockaddr *addr, socklen_t alen);

int
print_uptime(int sockfd)
{
    int n;
    char buf[BUFLEN];

    while ((n= recv(sockfd, buf, BUFLEN, 0)) > 0) {
        if (write(STDOUT_FILENO, buf, n) != n)
        return(-1);
    }
    if (n < 0)
        return(-1);
    if (n == 0)
        printf("nothing received/n");
    return(0);
}

int
main(int argc, char *argv[])
{
    struct addrinfo *ailist, *aip;
    struct addrinfo hint;
    struct sockaddr_in *sinp;
    int sockfd;
    int err;
    char seraddr[INET_ADDRSTRLEN];
    short serport;

    if (argc != 2) {
        printf("usage: %s <hostname>/n", argv[0]);
        exit(-1);
    }

    hint.ai_family = 0;
    hint.ai_socktype = SOCK_STREAM;
    hint.ai_flags = AI_CANONNAME;
    hint.ai_protocol = 0;
    hint.ai_addrlen = 0;
    hint.ai_addr = NULL;
    hint.ai_canonname = NULL;
    hint.ai_next = NULL;
    if ((err = getaddrinfo(argv[1], "ruptime", &hint, &ailist)) != 0) {
        printf("getaddrinfo error: %s/n", gai_strerror(err));
        exit(-1);
    }
    printf("getaddrinfo ok/n");
    for (aip = ailist; aip != NULL; aip = aip->ai_next) {
        sinp = (struct sockaddr_in *)aip->ai_addr;
        if (inet_ntop(sinp->sin_family, &sinp->sin_addr, seraddr, INET_ADDRSTRLEN) != NULL)
        {
            printf("server address is %s/n", seraddr);
        }
        serport = ntohs(sinp->sin_port);
        printf("server port is %d/n", serport);

        if ((sockfd = socket(aip->ai_family, SOCK_STREAM, 0)) < 0) {
            printf("create socket failed: %s/n", strerror(errno));
            exit(-1);
        }
        printf("create socket ok/n");
        if (connect_retry(sockfd, aip->ai_addr, aip->ai_addrlen) < 0) {
            printf("can't connect to %s: %s/n", argv[1], strerror(errno));
            exit(-1);
        }
        else {
            printf("connect ok/n");
            if (print_uptime(sockfd) < 0) {
                printf("print_uptime error: %s/n", strerror(errno));
                exit(-1);
            }
        }
    }
    exit(0);
}

2 以端口号的方式连接服务器:这个就有一点需要注意,hint的ai_flags不要设为AI_PASSIVE,因为返回的地址不是用来监听绑定的,一般设为AI_CANONNAME,代码就不贴了,照这上面的改改就可以了。

我自认为不太会写东西,并且由于种种原因,已经24小时没睡了,脑袋有点晕,再加上水平有限,所以有错误的地方兄弟们请指出来,另外有看不太明白的地方就跟帖,最后谢谢版主给我这个精,大家互相学习。

当然这只是利用getaddrinfo函数来写服务和客户程序。
原文地址:https://www.cnblogs.com/zechen11/p/2271268.html