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

相关推荐
大猫会长4 分钟前
调用codebuddy集成的supabase授权白屏解决方法
linux·运维·服务器
夜之眷属1 小时前
服务器被挖矿病毒入侵的排查与清理实录
运维·服务器
传人1 小时前
为什么 Xshell 中可以通过java -version查询到java 版本号码,Electerm 却查不到?
java·linux·服务器
陌上花开缓缓归以2 小时前
mebdlts3.4.1安全启动全流程
服务器·算法
鬼手点金2 小时前
opencode-全能开发者配置
java·linux·服务器·前端·javascript·学习·前向传播
在角落发呆2 小时前
软件配置备份方法:从手动到自动化的实践指南
windows·安全
阿明62 小时前
进程替换【Linux】
linux·运维·服务器
lingchen19063 小时前
Win 11 系统语言栏悬浮于桌面上影响操作感受,怎么取消?
windows
啦啦啦啦啦zzzz3 小时前
一致性哈希
服务器·算法·哈希算法·c++20·分布式存储
倔强的石头1063 小时前
【Linux指南】动静态库系列(十二):库工程发布与错误排查:从能跑到可维护
linux·运维·服务器