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

相关推荐
IOT.FIVE.NO.13 小时前
Claude code+Vscode+Remote ssh+ 服务器自定义第三方API配置保姆级教程
服务器·vscode·ssh
饿了吃洗衣凝珠3 小时前
【无标题】
运维·服务器·网络
染翰3 小时前
Linux 配置:应用用户执行 sudo su root 免密(运维标准配置)
linux·运维·服务器
一个人旅程~4 小时前
MacBook Pro安装Win11 IoT LTSC 2024的两种方法操作说明
windows·经验分享·macos·电脑
阿昭L5 小时前
Lab 3-1
windows·安全·逆向工程·恶意代码分析
wgc2k5 小时前
Node.js游戏服务器项目移植-2: 用TypeScript还是Javascript
服务器·游戏·node.js
草莓熊Lotso5 小时前
【Linux网络】深入理解 HTTP 协议(二):从协议格式到手写工业级 HTTP 服务器
linux·运维·服务器·网络·c++·http
上海云盾第一敬业销售6 小时前
服务器遭受攻击的应对策略及快速防护实践
运维·服务器·web安全·ddos
yyuuuzz12 小时前
独立站的技术基础与常见运维问题
大数据·运维·服务器·网络·数据库·aws
日取其半万世不竭16 小时前
iftop、nethogs 和 nload:Linux 服务器网络流量实时监控工具介绍
linux·运维·服务器