显示计算机名和 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP