Linux domain name resolution function gethostbyname and getaddrinfo

  

First, function prototype #include <netdb.h> struct hostent *gethostbyname (const char *name); role: can be used to resolve the domain name structure hostent prototype is as follows: struct hostent {char *h_name; char **h_aliases; int h_addrtype; int h_length; char **h_addr_list; } Example: #include <stdio.h>#include <stdlib.h>#include <sys/socket.h> #include <netinet/in.h>#include <netdb.h>int main(int argc, char **argv){if (argc != 2) {fprintf(stderr, "Usage: %s hostname\\ n",argv[1]);exit(1); }struct hostent *answer;int i;char ipstr[16];answer = gethostbyname(argv[1]);if (answer == NULL) {herror(" ;gethostbyname"); //The error handling function comes with gethostbyname exit(1);}for (i = 0; (answer->h_addr_list)[i] != NULL; i++) {inet_ntop(AF_INET, (answer ->h_addr_list)[i], ipstr, 16);printf("%s\ ", ipstr);printf("officail name : %s\ ", answer->h_name);}exit( 0);} Compile execution effect Root@ubuntu:/media/2-G/teacher code/20100427/inet_v4/stream# ./myhost www.hpu.edu.cn202.102.253.254officail name : www.hpu.edu.cn 2. Function prototype int getaddrinfo( Const char *node, const char *service, const struct addrinfo *hints,struct addrinfo **res); This function stores data in a linked list. Char *node is generally the domain name const char *service //service, can be NULLconst struct addrinfo *hints //pointing to the socket address structure returned by res struct addrinfo **res //pointing to the returned result example: #include < Stdio.h>#include <stdlib.h>#include <sys/socket.h>#include <netinet/in.h>#include <netdb.h>#include <string.h>int main (int argc, char **argv){if (argc != 2) {fprintf(stderr, "Usage: %s hostname\ ",argv[1]);exit(1); }struct addrinfo *answer, Hint, *curr;char ipstr[16]; bzero(&hint, sizeof(hint));hint.ai_family = AF_INET;hint.ai_socktype = SOCK_STREAM;int ret = getaddrinfo(argv[1], NULL, &hint , &answer);if (ret != 0) {fprintf(stderr,"getaddrinfo: &s\ ",gai_strerror(ret));exit(1);}for (curr = answer; curr != NULL; curr = curr->ai_next) {inet_ntop(AF_INET, &((( struct sockaddr_in *)(curr->ai_addr))->sin_addr), ipstr, 16);printf("%s\\ n", ipstr);}freeaddrinfo(answer);exit(0);}
zh-CN"],null,[0.9596082],zh-CN"]]]

Copyright © Windows knowledge All Rights Reserved