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

相关推荐
一条破秋裤7 小时前
Linux 共享内存通信:POSIX 共享内存与 mmap
linux·运维·服务器
贵州山魈羡民7 小时前
【玩转手机】通过 Podroid 上的 Alpine 部署 1Panel,把微型服务器装进口袋
运维·服务器
程序员-Benothing9 小时前
Shell输入输出详解:read、echo、printf、颜色输出
linux·运维·服务器
FPGA小徐10 小时前
从 NEMU 到 AbstractMachine:程序、运行时环境与 AM 完全解析
linux·运维·服务器
呉師傅11 小时前
得力P2500、M2500系列打印机硒鼓加粉及清零方法【纯享版】
运维·网络·windows·电脑
ZhangJun9512 小时前
从零写一个类鲁大师的硬件检测小工具,软件附上,可直接使用
windows·测试工具·电脑·笔记本电脑·硬件架构
..Dauntless..14 小时前
【Linux】进程地址空间初步理解
linux·运维·服务器
imperialeast14 小时前
创建WAV文件 韩文、德文、俄文等unicode音乐标签
windows·小程序
Julien200414 小时前
Docker 网络(一)
linux·运维·服务器·ssh·学习方法
易点云徐源14 小时前
社保费管理客户端打开后进度条卡20%,等待1分钟提示获取接收配置失败
windows