名字和数值地址间的转换:gethostbyname() gethostbyaddr()
struct hostent{ char * h_name; char * * h_aliases; int h_addrtype; int h_length; char * * h_addr_list; }; #define h_addr h_addr_list[0];
struct hostent * gethostbyname(const char * hostname);
int main(int argc,char ** argv){ char *ptr,**pptr; char str[INET6_ADDRSTRLEN]; struct hostent *hptr; while(--argc > 0){ ptr = *++argv; if((hptr=gethostbyname(ptr)) == NULL){ err_msg("gethostbyname error for host:%s:%s", ptr,hstrerror(h_errno)); continue; } }//给每个命令行参数调用gethostbyname() printf("official hostname:%s\n",hptr->h_name); //规范主机名输出 for(pptr=hptr->h_aliases;*pptr!=NULL;pptr++) printf("\tallias:%s\n",*pptr); switch(hptr->h_addrtype){ case AF_INET: #ifdef AF_INET6 case AF_INET6: #endif pptr = hptr->h_addr_list; for( ;*pptr != NULL;pptr++) //pptr只想一个指针数组,数组中每个指针都指向一个地址。 printf("\taddress:%s\n", inet_ntop(hptr->h_addrtype,*pptr,str,sizeof(str))); break; default: err_ret("unknown address type"); break; } exit(0); }
struct hostent * gethostbyaddr(const char *addr,size_t len,int family);
int uname(struct utsname * name);
char ** my_addrs(int * addrtype){ struct hostent *hptr; struct utsname myname; if(uname(&myname) < 0) return(NULL); if((hptr = gethostbyname(myname.nodename)) == NULL) return(NULL); *addrtype = hptr->haddrtype; return(hptr->h_addr_list); }
int gethostname(char *name,size_t namelen);
struct servent * getservbyname(const char * servname,const char * protoname); struct servent{ char * s_name; char * * s_aliases; int s_port; char * s_proto; };
struct servent * sptr; sptr = getservbyname("ftp","tcp"); sptr = getservbyname("ftp","udp"); //因为ftp仅支持TCP,因此会失败
struct servent * getservbyport(int port,const char * protname);//port必须为网络字节序
struct servent * sptr; sptr = getservbyport(htons(53),"udp");