解析域名,获取域名ip并输出到终端
/**
* author : 18312615416@163.com
* @function name: main
* @brief : 程序实现解析域名(如www.baidu.com),把获取到的域名的IP地址全部输出到终端
* @param : @argc : 终端输入参数的个数
: @argv[] : 终端输入的参数
* @date : 2024/06/05
* @version : 1.0
* @note : inet_ntoa(struct in_addr in)可把网络字节序的IP地址转换为字符串形式的点分十 进制IP
: gethostbyname()可获取域名结构
*/
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
int main(int argc,char *argv[])
{
struct hostent *host;
struct in_addr **addr_list;
int i;
//检查参数有效性
if (argc != 2)
{
fprintf(stderr, "argument is invaild ,errno:%d,%s\n",errno,strerror(errno));
exit(1);
}
// 获取域名的hostent结构
host = gethostbyname(argv[1]);
if (host == NULL)
{
// gethostbyname()返回NULL表示出错
perror("gethostbyname failed\n");
return -1;
}
//打印主机(百度)的官方名称
printf("Hostname: %s\n", host->h_name);
//h_addr_list为指向主机网络地址的指针数组,以空指针终止
addr_list = (struct in_addr **) host->h_addr_list;
// 遍历IP地址列表
for(i = 0; addr_list[i] != NULL; i++)
{
// 使用inet_ntoa()将网络字节序的IP地址转换为点分十进制的字符串形式
printf("IP Address : %s\n", inet_ntoa(*addr_list[i]) );
}
//遍历主机备用名称
for(i = 0;host->h_aliases[i] != NULL; ++i)
{
//打印主机备用名
printf("other hostname : %s\n",host->h_aliases[i]);
}
return 0;
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 上周热点回顾(2.17-2.23)