Linux下调用getaddrinfo失败


在学习APUE第16章关于网络IPC:套接字时,运行程序清单16-5时失败,错误信息如下:

   
  [ajaxhe@localhost sockets]$ ./ruptimed
  
ruptimed: getaddrinfo error: Servname not supported for ai_socktype

错误是来自getaddrinfo()函数调用失败,单从错误输出来看,是server name出了问题,请问下这个问题改如何解决?

源代码如下:

   
  #include <stdio.h>
  
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <sys/socket.h>
#include <netdb.h>
#include <errno.h>

#define BUFLEN 128
#define QLEN 10

#ifndef HOST_NAME_MAX
#define HOST_NAME_MAX 256
#endif

extern int initserver(int, struct sockaddr *, socklen_t , int);

void
serve(int sockfd)
{
int clfd;
FILE *fp;
char buf[BUFLEN];

for(;;) {
clfd = accept(sockfd, NULL, NULL);
if(clfd < 0) {
syslog(LOG_ERR, "ruptime: accept error:%s",
strerror(errno));
exit(1);
}
if((fp = popen("/usr/bin/uptime", "r")) == NULL) {
sprintf(buf, "error:%s\n", strerror(errno));
send(clfd, buf, strlen(buf), 0);
} else {
while(fgets(buf, BUFLEN, fp) != NULL)
send(clfd, buf, strlen(buf), 0);
pclose(fp);
}
close(clfd);
}
}

int
main(int argc, char *argv[])
{
struct addrinfo *ailist, *aip;
struct addrinfo hint;

int sockfd, err, n;
char *host;

if(argc != 1) {
printf("usage: ruptimed");
exit(1);
}

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

n = HOST_NAME_MAX;
host = malloc(n);
if(host == NULL) {
perror("malloc error");
exit(1);
}

/* daemonize("ruptimed"); */
hint.ai_flags = AI_CANONNAME;
hint.ai_family = 0;
hint.ai_socktype = SOCK_STREAM;
hint.ai_protocol = 0;
hint.ai_addrlen = 0;
hint.ai_canonname = NULL;
hint.ai_next = NULL;

if((err = getaddrinfo(host, "ruptime", &hint, &ailist)) != 0) {
syslog(LOG_ERR, "ruptimed: getaddrinfo error: %s", gai_strerror(err));
exit(1);
}
for(aip = ailist; aip != NULL; aip = aip->ai_next) {
if((sockfd = initserver(SOCK_STREAM, aip->ai_addr, aip->ai_addrlen, QLEN)) >= 0) {
serve(sockfd);
exit(0);
}
}
exit(1);
}

Linux 网络编程

BorisX 11 years, 9 months ago

出现这种原因是因为没有给服务分配端口号,可以手动添加端口号,就是在/etc/services文件里加上一行:

   
  ruptime   4000/tcp
 

具体可以参考http://blog.csdn.net/andyxie407/article/details/1672325

钢铁同志的咆哮 answered 11 years, 9 months ago

Your Answer