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

相关推荐
江华森12 分钟前
操作系统与 Linux 内核实战教程
linux·运维·服务器
旺王雪饼 www21 分钟前
localStorage 和 sessionStorage区别与联系
服务器·前端·javascript
大树8841 分钟前
PUE 超 1.35 要多交多少?存量机房液冷改造 3 张算账表
大数据·运维·服务器·人工智能
小此方1 小时前
Re:Linux系统篇(二十八)文件篇·一:理解 Linux 文件基础I/O、Linux 文件操作与系统调用机制
linux·运维·服务器
likerhood1 小时前
Linux 服务器基础资源查看:CPU、GPU、内存、磁盘与一键检测脚本
linux·运维·服务器
流浪0012 小时前
Linux系统篇(三):Linux 命令行参数 & 环境变量:程序和系统沟通的底层逻辑
linux·运维·服务器
yyuuuzz2 小时前
AI模型部署中的常见稳定性问题
运维·服务器·网络·数据库·人工智能·云计算·github
caimouse2 小时前
Reactos 第 4 章 对象管理 — 4.2 对象类型(Object Type)
c语言·windows·架构
STDD2 小时前
V Rising《夜族崛起》 专用服务器搭建教程
运维·服务器
Ameilide2 小时前
Linux 应用软件编程 多任务并发
linux·运维·服务器