UNIX環境編程------Unix編程實例------Gethostbyname和gethostname結合使用打印出主機IP地址

Gethostbyname和gethostname結合使用打印出主機IP地址:

 

   源代碼:

                  

#include<unistd.h>

#include<netinet/in.h>

#include<sys/socket.h>

#include<stdio.h>

#include<errno.h>

#include<netdb.h>

#include<stdlib.h>

 

 

 

int main()

{

         charname [50];

         intgethnrvl;

         inti=0;

 

         struct  hostent* hostent_t;

        

         gethnrvl=gethostname(name,sizeof(name));

         if(gethnrvl==-1)

           {

                   perror("gethostnameerror");

                   _exit(-1);

          }

printf("%s \n",name);

 

//使用gethostbyname獲取 主機IP

 

 hostent_t =gethostbyname(name);

 

//打印出IP地址

 

 

for(;hostent_t->h_addr_list[i];i++)

         {

                            printf("%s/t",inet_ntoa(*(struct in_addr*)(hostent_t->h_addr_list[i])));

         }

           

 

}

運行結果:

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章