printf 地址_C程序显示主机名和IP地址
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                printf 地址_C程序显示主机名和IP地址
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                查找本地計算機的主機名和IP地址的方法有很多。這是使用C程序查找主機名和IP地址的簡單方法。
我們將使用以下功能:
gethostname() :gethostname函數檢索本地計算機的標準主機名。
gethostbyname() :gethostbyname函數從主機數據庫中檢索與主機名相對應的主機信息。
inet_ntoa():inet_ntoa函數將(Ipv4)Internet網絡地址轉換為Internet標準點分十進制格式的ASCII字符串。
// C program to display hostname // and IP address #include #include #include #include #include #include #include #include #include // Returns hostname for the local computer void checkHostName(int hostname) { if (hostname == -1) { perror("gethostname"); exit(1); } } // Returns host information corresponding to host name void checkHostEntry(struct hostent * hostentry) { if (hostentry == NULL) { perror("gethostbyname"); exit(1); } } // Converts space-delimited IPv4 addresses // to dotted-decimal format void checkIPbuffer(char *IPbuffer) { if (NULL == IPbuffer) { perror("inet_ntoa"); exit(1); } } // Driver code int main() { char hostbuffer[256]; char *IPbuffer; struct hostent *host_entry; int hostname; // To retrieve hostname hostname = gethostname(hostbuffer, sizeof(hostbuffer)); checkHostName(hostname); // To retrieve host information host_entry = gethostbyname(hostbuffer); checkHostEntry(host_entry); // To convert an Internet network // address into ASCII string IPbuffer = inet_ntoa(*((struct in_addr*) host_entry->h_addr_list[0])); printf("Hostname: %s", hostbuffer); printf("Host IP: %s", IPbuffer); return 0; }輸出:
Hostname: cContainerHost IP: 10.98.162.101輸出因機器而異。
總結
以上是生活随笔為你收集整理的printf 地址_C程序显示主机名和IP地址的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: linux vi撤销上一个命令(linu
- 下一篇: 安卓主题制作软件(安卓主题制作)
