顯示計算機名和 IP 地址的 C 程式


在本節,我們將瞭解如何以更簡單的方式檢視本地系統的計算機名和 IP 地址。我們將編寫一個 C 程式來查詢計算機名和 IP

使用了以下一些函式。這些功能有不同的作用。讓我們看看這些函式及其功能。

函式說明
gethostname()它為本地計算機查詢標準計算機名。
gethostbyname()它從主機資料庫中查詢與計算機名相對應的主機資訊
iten_ntoa()它將 IPv4 Internet 網路地址轉換為點分十進位制格式的 ASCII 字串。

示例程式碼

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
void check_host_name(int hostname) { //This function returns host name for
   local computer
   if (hostname == -1) {
      perror("gethostname");
      exit(1);
   }
}
void check_host_entry(struct hostent * hostentry) { //find host info from
   host name
   if (hostentry == NULL) {
      perror("gethostbyname");
      exit(1);
   }
}
void IP_formatter(char *IPbuffer) { //convert IP string to dotted decimal
   format
   if (NULL == IPbuffer) {
      perror("inet_ntoa");
      exit(1);
   }
}
main() {
   char host[256];
   char *IP;
   struct hostent *host_entry;
   int hostname;
   hostname = gethostname(host, sizeof(host)); //find the host name
   check_host_name(hostname);
   host_entry = gethostbyname(host); //find host information
   check_host_entry(host_entry);
   IP = inet_ntoa(*((struct in_addr*) host_entry->h_addr_list[0]));
   //Convert into IP string
   printf("Current Host Name: %s
", host); printf("Host IP: %s
", IP); }

輸出(在 Linux 系統上測試)

Current Host Name: soumyadeep-VirtualBox
Host IP: 127.0.1.1

更新於:2019-07-30

3K+ 瀏覽

開啟您的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.