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

相关推荐
爱写代码的阿森1 小时前
鸿蒙三方库 | harmony-utils之RegexUtil正则匹配验证详解
服务器·华为·harmonyos·鸿蒙·huawei
雨的旋律20992 小时前
ubuntu2604
linux·运维·服务器
王维同学2 小时前
Credential Provider、Filter 与 PLAP 的 CLSID 枚举
c++·windows·安全·注册表
三言老师2 小时前
mkdir创建多级目录,目录创建基础实操
linux·运维·服务器
imc.113 小时前
linux EXT文件系统
linux·运维·服务器
寒水馨4 小时前
Windows下载、安装 Codex CLI(附安装包codex-x86_64-pc-windows-msvc.exe)
windows·rust·codex·终端工具·自动化编程·codex cli·ai编码代理
三言老师4 小时前
mv移动文件、重命名文件实战案例
linux·服务器·网络·centos
向夏威夷 梦断明暄5 小时前
C# 弃元模式:从语法糖到性能利器的深度解析
服务器·数据库·c#
一叶之秋14125 小时前
Linux网络初识
linux·服务器·网络
熬夜苦读学习6 小时前
Qt常用控件
服务器·开发语言·qt