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

相关推荐
TG:@yunlaoda360 云老大2 小时前
华为云国际站代理商GES的图引擎服务有哪些优势?
服务器·数据库·华为云
QQ__17646198248 小时前
Ubuntu系统创建新用户与删除用户
linux·运维·服务器
渣渣盟9 小时前
Linux邮件服务器快速搭建指南
linux·服务器·开发语言
6极地诈唬9 小时前
【PG漫步】DELETE不会改变本地文件的大小,VACUUM也不会
linux·服务器·数据库
谷雨不太卷9 小时前
Linux_文件权限
linux·运维·服务器
驱动开发00711 小时前
Windows_Hello_Configuration_Analysis Windows Hello 配置过程分析 setup包分析
windows·驱动开发·云计算·计算机外设·usb重定向
Xの哲學11 小时前
Linux SLAB分配器深度解剖
linux·服务器·网络·算法·边缘计算
weixin_4397062511 小时前
JAVA版日语50音训练(读音强化记忆)
windows
阿蒙Amon11 小时前
C#每日面试题-简述C#访问修饰符
windows·microsoft·c#
齐鲁大虾12 小时前
UOS(统信操作系统)如何更新CUPS(通用Unix打印系统)
linux·服务器·chrome·unix