程序显示主机名和IP地址C
在本节中,我们将看到如何以更简单的方式查看本地系统的主机名和IP地址。我们将编写一个C程序来查找主机名和IP。
使用了以下一些功能。这些功能具有不同的任务。让我们看一下功能及其任务。
示例
#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\n", host);
printf("Host IP: %s\n", IP);
}输出结果
Current Host Name: soumyadeep-VirtualBox Host IP: 127.0.1.1
热门推荐
1 潜能开发训练狗狗
2 狗狗多会训练好
3 扣篮训练狗狗
5 狗狗不训练
6 少儿柔术训练狗狗
8 训练好狗狗
9 训练狗狗怎么训
10 狗狗训练猫咪
11 狗狗训练地点
12 两个多月的狗狗怎么训练
13 怎么训练狗狗去厕所拉屎
14 狗狗怎样训练大小便
15 训练狗狗母
16 怎么训练狗狗坐下和握手
17 近视训练狗狗
18 狗狗倒的训练