Unix Network Programming Episode 76

We encourage the use of getaddrinfo (Section 11.6(See 8.9.6)) in new programs.

复制代码
#include <netdb.h>
struct hostent *gethostbyname (const char *hostname);

The non-null pointer returned by this function points to the following hostent structure:

复制代码
struct hostent {
	char *h_name; /* official (canonical) name of host */
	char **h_aliases; /* pointer to array of pointers to alias names */
	int h_addrtype; /* host address type: AF_INET */
	int h_length; /* length of address: 4 */
	char **h_addr_list; /* ptr to array of ptrs with IPv4 addrs */
};

gethostbyname differs from the other socket functions that we have described in that it does not set errno when an error occurs. Instead, it sets the global integer h_errno to one of the following constants defined by including <netdb.h>:

  • HOST_NOT_FOUND
  • TRY_AGAIN
  • NO_RECOVERY
  • NO_DATA (identical to NO_ADDRESS)

The NO_DATA error means the specified name is valid, but it does not have an A record. An example of this is a hostname with only an MX record.

Most modern resolvers provide the function hstrerror, which takes an h_errno value as its only argument and returns a const char * pointer to a description of the error.

复制代码
#include "unp.h"

int main(int argc, char **argv)
{
    char *ptr, **pptr;
    char str[INET_ADDRSTRLEN];
    struct hostent *hptr;

    while(--argc>0)
    {
        ptr=*++argv;
        if((hptr=gethostbyname(ptr)==NULL)
        {
            err_msg("gethostbyname error for host: %s: %s",ptr, hstrerror,(h_errno));
        }
        continue;
    }
    printf("official hostname: %s\n", hptr->h_name);

    for(pptr=hptr->h_aliases;*pptr!=NULL;pptr++)
        printf("\talias:%s\n", *pptr);
    
    switch(hptr->h_addrtype)
    {
        case AF_INET:
            pptr=hptr->h_addr_list;
            for(;*pptr!=NULL;pptr)
            {
                printf("\taddress: %s\n",Inet_ntop(hptr->h_addrtype,*pptr, str, sizeof(str)));
            }
            break;
        default:
            err_ret("unknown address type");
            break;
    }
    return 0;
}

Call gethostbyname and print returned information

相关推荐
skywalk816313 小时前
在 Windows 系统中,可以通过修改 VSCode 的用户数据目录和扩展目录来将插件(扩展)安装到非 C 盘
windows
虾壳云管家14 小时前
OpenClaw 2.6.6 从部署到技能使用一站式攻略
人工智能·windows·openclaw·openclaw一键部署教程·openclaw安装教程
春蕾夏荷_72829772514 小时前
1、c++ acl udp服务器客户端简单实例-服务器端(1)
服务器·c++·udp
楼田莉子14 小时前
Linux网络:数据链路层
linux·服务器·开发语言·网络·c++·后端
发现你走远了14 小时前
Windows 下使用 pyenv-win:安装、迁移到 D 盘、配置镜像源与多版本切换实战
windows·pyenv-win
fish_xk14 小时前
Linux基础指令。
linux·运维·服务器
艾莉丝努力练剑14 小时前
【Linux网络】Linux 网络编程入门:UDP Socket 编程(上)
linux·运维·服务器·网络·c++·udp
代码中介商14 小时前
Linux多线程编程完全指南:线程同步、互斥锁与生产者消费者模型
linux·运维·服务器
(Charon)14 小时前
【C++/Qt】Qt 实现 POP3/IMAP 邮件测试工具:连接邮箱服务器、登录与读取邮件
服务器·开发语言·c++
可视化运维管理爱好者15 小时前
rg完整中文操作指南
linux·运维·服务器·ai