这是我们在这一章将会学习的重要的一个函数。这个函数接受我们希望解析的主机名,然后返回一个以各种方式标识的结构。这个函数的概要如下: #include extern int h_errno; struct hostent *gethostbyname(const char *name);
函数gethostbyname接受一个代表我们希望解析为地址的主机名的C字符串作为输入参数。如果函数调用成功会返回一个指向hostent结构的指针。如果函数失败,则会返回一个NULL指针,而错误原因将会存放在变量h_errno中。 hostent结构如下: struct hostent { char *h_name; /* official name of host */ char **h_aliases; /* alias list */ int h_addrtype; /* host address type */ int h_length; /* length of address */ char **h_addr_list; /* list of addresses */ }; /* for backward compatibility */ #define h_addr h_addr_list[0]
/* * This function report the error and * exits back to the shell: */ static void bail(const char *on_what) { if(errno != 0) { fputs(strerror(errno),stderr); fputs(": ",stderr); } fputs(on_what,stderr); fputc('\n',stderr); exit(1); }
int main(int argc,char **argv) { int z; char *srvr_addr = NULL; char *srvr_port = "9099"; struct sockaddr_in adr_srvr; /* AF_INET */ struct sockaddr_in adr_clnt; /* AF_INET */ int len_inet; /* length */ int s; /* Socket */ int c; /* Client socket */ int n; /* bytes */ time_t td; /* current date&time */ char dtbuf[128]; /* Date/Time info */ FILE *logf; /* Log file for the server */ struct hostent *hp; /* Host entry ptr */
/* * Open the log file: */ if(!(logf = fopen("srvr2.log","w"))) bail("fopen(3)");
/* * Use a server adderss from the command * line,if one has been provided. * Otherwise,this program will default * to using the arbitrary address * 127.0.0.1: */ if(argc>=2) { /* Addr on cmdline: */ srvr_addr = argv[1]; } else { /* Use default address :*/ srvr_addr = "127.0.0.1"; }
/* * If there is a second argument on the * command line,use it as the port #: */ if(argc>=3) srvr_port = argv[2];
/* * Create a TCP/IP socket to use: */ s = socket(PF_INET,SOCK_STREAM,0); if(s==-1) bail("socket()");