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

相关推荐
H.莓飛7 小时前
【C++】【STL】stack_OJ题
服务器·c语言·开发语言·数据结构·c++·算法·visual studio
无足鸟ICT10 小时前
【RHCA+】sosreport(收集诊断文档)
linux·运维·服务器
Vex2une12 小时前
JDK 8 下载安装与环境变量配置完整指南(Windows新手图文教程)
java·windows·环境配置·环境变量·jdk8·jdk下载安装·java入门教程
瑞雪兆丰年兮13 小时前
Linux零基础快速入门-第二章 Linux基础命令
linux·运维·服务器
光电笑映16 小时前
TCP 为什么可靠?从三次握手、滑动窗口到拥塞控制全面拆解(上)
运维·服务器·网络·udp
飞奔的瓜牛16 小时前
Linux 下使用 OpenSSL 生成自签名证书完整指南
运维·服务器·nginx
星空孤辰17 小时前
【camera 008】android camera id 注册、状态监控等状态变化 全流程梳理
android·windows
全方位办公软件18 小时前
Windows音频服务架构解析:AudioSrv与AudioEndpointBuilder排障
windows·命令行·powershell·音频服务·驱动修复·mmdevices·audiosrv
峥嵘life18 小时前
Android16 热点「网络共享」开关的设计与实现
服务器·网络·microsoft
张小姐的猫19 小时前
【基于 WebSocket 的多用户网页五子棋】—— 整合封装服务器模块设计实现1️⃣
服务器·websocket·网络协议