C 程序来显示主机名和 IP 地址
在本节中,我们将看到如何以更简单的方式查看本地系统的主机名和IP地址。我们将编写一个C程序来查找主机名和IP。
使用了以下一些功能。这些功能有不同的任务。让我们看看功能和它们的任务。
示例代码
#include#include #include #include #include #include #include #include #include void check_host_name(int hostname) { //此函数返回主机名 local computer if (hostname == -1) { perror("gethostname"); exit(1); } } void check_host_entry(struct hostent * hostentry) { //从中查找主机信息 host name if (hostentry == NULL) { perror("gethostbyname"); exit(1); } } void IP_formatter(char *IPbuffer) { //将IP字符串转换为点分十进制 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)); //找到主机名 check_host_name(hostname); host_entry = gethostbyname(host); //查找主机信息 check_host_entry(host_entry); IP = inet_ntoa(*((struct in_addr*) host_entry->h_addr_list[0])); //转换成IP字符串 printf("Current Host Name: %s\n", host); printf("Host IP: %s\n", IP); }
输出(在Linux系统上测试)
Current Host Name: soumyadeep-VirtualBox Host IP: 127.0.1.1
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下