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

相关推荐
楼田莉子4 小时前
C#学习:分支与循环
服务器·后端·学习·c#
徐安安ye4 小时前
KV Cache的生老病死:FlashAttention里的显存管理全流程
java·服务器·前端
A懿轩A4 小时前
Claude Code 2026 最新版下载安装教程详细版 涵盖Windows 和 MacOS 安装 附常见问题解决方案
windows·macos
Mortalbreeze4 小时前
进程间通信 ---- 基于管道来实现
linux·服务器
dhjabc_15 小时前
Windows 超完整配置 OpenCode 教程(改D盘安装+永久国内镜像+全套使用指南)
windows
MepSUxjvy5 小时前
拆解 OpenHands(11)--- Runtime主要组件
java·windows·microsoft
Bert.Cai5 小时前
Linux sort命令详解
linux·运维·服务器
开开心心就好5 小时前
免费无广告的批量卸载与系统清理工具
linux·服务器·网络·智能手机·rabbitmq·excel·memcached
倔强的石头1065 小时前
SenseNova-U1 实战体验:从网页版生成,到 Mac 踩坑,再到 CUDA 服务器跑通本地部署
运维·服务器·macos
l16775168545 小时前
天翼云服务器失联排查完整报告_事件报告
运维·服务器·云原生·云计算