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

相关推荐
啊啊啊啊啊!!!!24 分钟前
【Linux】初始Linux操作系统
linux·运维·服务器
数字新视界34 分钟前
信创动环监控厂家深入剖析智能机房环境监控技术应用与挑战
服务器·数据库·物联网·芯片·动环监控系统
2401_894915531 小时前
新手落地 Geo 优化:源码下载、依赖安装、数据库初始化完整步骤
运维·服务器·数据库·人工智能·缓存·开源
fruge1 小时前
Windows部署MiGPT GUI:小爱音箱接入大模型、TTS与自定义人设
windows
杨云龙UP1 小时前
Oracle ASH 报告详解:与 AWR 的区别、使用场景及生成方法
linux·运维·服务器·数据库·oracle
黑泽明*2 小时前
LVS-Keepalived-全解析
服务器·开发语言·笔记·学习·php
源码学社2 小时前
DeerFlow Windows 本地运行教程(uv)
windows·uv·沙箱·deerflow·超级智能体·deerflow安装
琥珀色糖2 小时前
Linux makefile
linux·运维·服务器·makefile·make
Sombra_Olivia2 小时前
复现Windows Server服务RPC请求缓冲区溢出漏洞(MS08067)
网络·windows·安全·web安全·网络安全·渗透测试·vulhub
2401_894915532 小时前
Geo 优化源码部署避坑指南:解决访问异常、定位失效、收录卡顿问题
java·服务器·后端·缓存·开源