查询主机的IP程序

参考unp第11章的 hostserv程序

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

struct addrinfo *host_serv(const char *hostname,const char *service,int family,int sockettype)
{
  int n;
  struct addrinfo  hints,*res;

  bzero(&hints,sizeof(struct addrinfo));
  hints.ai_flags = AI_CANONNAME;
  hints.ai_family = family;
  hints.ai_socktype = sockettype;

  if((n = getaddrinfo(hostname,service,&hints,&res))!=0)
   return NULL;
 
 return res;
}

int main(int argc,char *argv[])
{
 if(argc != 2)
 {
  printf("usage: hostserv hostname\n");
  return -1;
 }
 struct addrinfo *test;
 test = host_serv(argv[1],NULL,AF_INET,SOCK_STREAM);
 while(test != NULL)
 {
  if( test -> ai_family == AF_INET)
  {
   struct sockaddr_in *sin = (struct sockaddr_in *) test-> ai_addr;
   printf("%s\n", inet_ntoa( sin -> sin_addr));
   test = test -> ai_next;
  }
 }
 return 0;
}
转载请注明来源:Leoncom-《查询主机的IP程序》
Trackback

no comment untill now

Add your comment now