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

相关推荐
.Bryce.20 分钟前
从强化学习到Agentic RL:让Agent在“干活“中自己变聪明
服务器·网络·agent·rag·agentic rl
ZYH_060120 分钟前
rhcsa课程复习题
服务器·bash
用户5651903944928 分钟前
高危 编号99999漏洞情报(26年8-10月) 多个严重漏洞:PHP执行远程控制代码 / Linux虚拟机-宿主越界(CVE-2026-99999...
服务器
云飞云共享云桌面34 分钟前
广东东莞制造工厂10人共享一台三维设计服务器
运维·服务器·3d·自动化·制造
A1Book2 小时前
Win11 开机项治理方案:四层扫描、分级决策与可回滚落地
windows
hz567892 小时前
企业视频会议系统方案:总部与分支机构高效协同如何落地?
运维·服务器·网络·安全·实时音视频·信息与通信
网络小江3 小时前
组网第27课:ARP 的能与不能——免费 ARP、代理 ARP 与 ARP 欺骗
服务器·网络·网络安全·负载均衡·免费arp
云计算练习生3 小时前
什么是文件权限?Linux 中 rwx 与数字权限的对应关系
linux·运维·服务器·操作系统·文件权限管理
FY@-@3 小时前
VMware ESXi 7.0 实验全记录:嵌套安装 → 网络配置 → 存储 → Windows 10 虚拟机部署
运维·网络·windows·云计算