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

相关推荐
无奈笑天下8 小时前
Linux上kdump故障标准处理流程
linux·运维·服务器·github
瑞雪兆丰年兮12 小时前
Linux快速入门 第四章 Linux系统常用操作技巧
linux·运维·服务器
星恒随风12 小时前
从0实现C++ AI大模型接入SDK(四):大模型API接入、公共数据结构设计与日志库封装
linux·服务器·数据结构·c++·人工智能
时间的拾荒人13 小时前
Linux进程间通信(上篇):匿名管道 +进程池(基于匿名管道实现)
linux·服务器·管道
无足鸟ICT13 小时前
【RHCA+】介绍proc
linux·运维·服务器
布莱克60516 小时前
Swift 下标(Subscript)详解:从语法到实战
服务器·开发语言·ios·ssh·swift·下标
柳鲲鹏18 小时前
编译Windows版本的zlib
windows
charliejohn19 小时前
计算机考研 408 网络 DNS 概念
运维·服务器·网络
Name_NaN_None19 小时前
安卓手机远程控制电脑方法(Android/Windows) —— 「小白教程」
android·windows·智能手机·电脑·笔记本
Kainy21 小时前
93条CVE怎么核对?用Syft生成SBOM加Grype匹配,把服务器漏洞排查从体力活变成三步自动化
运维·服务器·自动化