Linux网络编程之域名解析(DNS)

Be open to learning new lessons even if they contradict the lessons you learned yesterday.--------敞开心胸学习新的东西,即使他与你昨天学到的互相矛盾。

1, 预备知识

我们平常往往都是通过网站的域名上网,那我们如何使用程序获取相应服务器的公网IP呢?
今天我们就编写这么一个程序。

关键在gethostbyname()函数,下面是结构体:

 struct hostent {
        char    *h_name;        /* official name of host */
        char    **h_aliases;    /* alias list */
        int     h_addrtype;     /* host address type */
        int     h_length;       /* length of address */
        char    **h_addr_list;  /* list of addresses */
  }

如果忘记了命令函解析,可以阅读:
https://blog.csdn.net/weixin_46027505/article/details/104430092

2, 不含命令函解析的代码

  • 我们先编写一个不含命令行解析的baidu.c 用于解析百度的ip地址
#include <stdio.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <getopt.h>

#define web "baidu.com"
int main(int argc, char *argv[])
{
    struct          hostent *p;
    int              i;
    char            *serv_ip = NULL;



    p = gethostbyname(web);
    printf("domai name: %s\n", p->h_name);

//接收一个in_addr结构体类型的参数并返回一个以点分十进制格式表示的IP地址字符串
    serv_ip = inet_ntoa(*(struct in_addr*)p->h_addr);
    printf("serv_ip: %s\n", serv_ip);

    return 0;
}

在这里插入图片描述

3, 含命令行解析的代码

#include <stdio.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <getopt.h>

int main(int argc, char *argv[])
{
    int             ch=0;
    struct          hostent *p;
    int             i;
    char            *serv_ip = NULL;

    struct   option        opts[] =
    {
     {"domain_name", required_argument, NULL, 'd'},
     {0, 0, 0, 0}
    };

     while( (ch=getopt_long(argc, argv, "d:", opts, NULL)) != -1 )
     {
         switch(ch)
         {
            case 'd':
            serv_ip=optarg;
            break;
         }
     }


    p = gethostbyname(serv_ip);
    printf("domai name: %s\n", p->h_name);
    printf("\n");
//打印所有ip地址
    for (i = 0; p->h_addr_list[i]; i++)
    {
        printf("ip address: %s \n", inet_ntoa(*(struct in_addr *)p->h_addr_list[i]));
    }
    printf("\n");

    serv_ip = inet_ntoa(*(struct in_addr*)p->h_addr);
    printf("serv_ip: %s\n", serv_ip);

    return 0;
}

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值