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

相关推荐
一匹电信狗5 分钟前
【C++11】Lambda表达式+新的类功能
服务器·c++·算法·leetcode·小程序·stl·visual studio
小苏兮10 分钟前
【把Linux“聊”明白】进程的概念与状态
linux·运维·服务器·学习
楼田莉子34 分钟前
C++/Linux小项目:自主shell命令解释器
linux·服务器·开发语言·c++·后端·学习
杜子不疼.37 分钟前
【Linux】网络编程入门:从一个小型回声服务器开始
linux·服务器·网络
魏 无羡1 小时前
windows 安装mysql(多个版本同时安装)
windows·mysql·adb
龙泉寺天下行走2 小时前
[Powershell入门教程]第4天:模块、脚本编写、错误处理与 .NET 集成
java·服务器·前端
Monody_R2 小时前
rhce作业
linux·服务器·apache
q***71852 小时前
海康威视摄像头RTSP使用nginx推流到服务器直播教程
运维·服务器·nginx
EasyCVR3 小时前
视频汇聚平台EasyCVR:构建通信基站“可视、可管、可控”的智慧安防体系
服务器·数据库·音视频
q***04053 小时前
自己编译RustDesk,并将自建ID服务器和key信息写入客户端
运维·服务器