//這是用來測試一個gethostbyname函數 用於使用域名獲取ip #include<stdio.h> #include<winsock2.h> #pragma comment(lib,"WS2_32.lib") #include<Ws2tcpip.h> #pragma comment(lib,"Ws2_32.lib") #include<stdlib.h> /* struct hostent { char *h_name; //域名 char ** h_aliases; //別名 short h_addrtype; //ip類型 是v4還是v6 v4(AF_INET) short h_length; //地址長度:4 但是我的輸出啥子都沒得 char ** h_addr_list; //注意這玩意是一個雙指針的東西 unp p240有圖 }; */ int main(void) { struct hostent* ent; int i = 0 ; char *ptr = "baidu.com"; char src[32] ={0}; WSADATA wd; //win下面必須這樣 因為懶得開linux所以就用vs if(WSAStartup(MAKEWORD(2,2),&wd) != 0) //WSAStartup { printf("WSAStartup error!"); system("pause"); return 1; } //檢查返回值錯誤問題 if((ent = gethostbyname(ptr)) == NULL){ fprintf(stderr , "gethostbyname error!"); system("pause"); exit(1); } fprintf(stdout , " h_name:%s\n" , ent->h_name); while(ent->h_aliases[i]) fprintf(stdout , " h_aliases[i%d]:%s\n",i , ent->h_aliases[i++]); fprintf(stdout , "h_addrtype : %s\n" ,(ent->h_addrtype == AF_INET)?"ipv4":"ipv6"); fprintf(stdout , "h_length : %h\n" , ent->h_length); //將ent結構體中的網絡字節序轉成 主機字節序 InetNtop(ent->h_addrtype , ent->h_addr_list[0], src , 32); //InetNtop( if(src[0] == NULL){ fprintf(stderr , " error ! null\n"); system("pause"); exit(2); } fprintf(stdout , "h_addr: %s\n" , src); system("pause"); exit(0); }
代碼說明一切 如果您發現錯誤或者改進的地方,請留言。不要吝嗇賜教!特此感謝
