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

相关推荐
日日行不惧千万里35 分钟前
绕过微软联网账号限制:用本地用户安装 Windows 11 的最新 3 种方法
windows·microsoft
java_logo1 小时前
Docker 部署 MinIO 全指南
运维·windows·mongodb·docker·容器
拾光Ծ1 小时前
【Linux】“ 权限 “ 与相关指令
linux·运维·服务器
歪歪1001 小时前
React Native开发有哪些优势和劣势?
服务器·前端·javascript·react native·react.js·前端框架
To_再飞行1 小时前
Linux Bash(一)
linux·运维·服务器·bash
黄雄进2 小时前
Windows使用docker安装milvus的配置文件
windows·docker·milvus
孤廖2 小时前
C++ 模板再升级:非类型参数、特化技巧(含全特化与偏特化)、分离编译破解
linux·服务器·开发语言·c++·人工智能·后端·深度学习
文火冰糖的硅基工坊2 小时前
[人工智能-大模型-9]:大模型十大应用场景和对应的代表性的产品?
服务器·人工智能·大模型
TG_yunshuguoji2 小时前
亚马逊云代理商:AWS怎么通过加密实现数据保护目标?
服务器·云计算·aws
可涵不会debug2 小时前
UU远程深度测评:重构远程控制体验的“无套路”标杆
运维·服务器