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

相关推荐
BlueAsia_Lab4 分钟前
华为 SuperCharge 认证,覆盖哪些产品?全品类梳理
运维·服务器·华为
H_oRIZoN_5 分钟前
Linux入门DAY32(文件 IO、进程、线程、IPC 通信)
linux·运维·服务器
0+1116 分钟前
Linux --Ext系列文件系统
linux·运维·服务器
Yang961111 分钟前
一台顶三台:鼎讯DLJ-1在不同故障类型中的模式切换数据复盘
服务器·网络·数据库
潘正翔16 分钟前
Memcached构建缓存服务器
运维·服务器·数据库·缓存·云原生·memcached
醉颜凉1 小时前
Elasticsearch服务器部署:从零到一完整启动+配置教程
大数据·服务器·elasticsearch
攻城有术1 小时前
专项攻克——研发排查Linux各类问题命令+实战案例
linux·运维·服务器
软件资深者1 小时前
千千静听典藏修复版 使用教程:经典本地音乐播放器回归,歌词同步、皮肤皮肤自由换,音乐播放器怀旧新手 5 分钟上手(2026)
windows
M158227690552 小时前
三格串口服务器:RS232/485 设备联网解决方案
运维·服务器·单片机
captain3762 小时前
文件与IO(2)
java·开发语言·windows·java-ee