linux下关于gethostbyname函数的使用

关于Linux域下的域名解析函数gethostbyname()的使用

gethostbyname()原型:struct hostent* gethostbyname(const char *name);

调用函数成功返回一个hostent结构体
struct hostent
{
char *h_name;
char ** h_aliases;
short h_addrtype;
short h_length;
char ** h_addr_list;
};

这里直接上代码

/*************************************************************************
    > File Name: dns.c
    > Author: malunkun
    > Mail: malunkun<209446860qq.com> 
    > Created Time: 2019年01月15日 星期二 14时13分53秒
 ************************************************************************/

#include<stdio.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdlib.h>
#include<errno.h>
#include<sys/types.h>  
#include<sys/socket.h>
#include<signal.h>
#include<unistd.h>
#include<netdb.h>
#include<string.h>
#include <arpa/inet.h>

int main(int argc,char *argv[])
{
	int optret;
	char *ipname = NULL;
	char ip[50];
	struct hostent *gethost = NULL;
	int file_fd;
	char buf[50];
	char *ptrf;
	char *ptrb;
	int n;
	char fptr[50];
	const char *ptr = NULL;
	struct in_addr  inAddr;
	while((optret = getopt(argc,argv,"i:p:")) != -1)
	{
		switch(optret)
		{
			case 'i':
				ipname = optarg;
				printf("option = i,the ipname is:%s\n",optarg);
				break;
			case 'p':
 	//			printf("option = p,the port will be set=%s\n",optarg);
				break;
		}
	}
	gethost = gethostbyname(ipname);
	if (NULL == gethost)
	{
		perror("get ipaddr fail!");
		return -1;
	}
	printf("get host successfully!\n");
	memset(ip,0,sizeof(ip));
	//printf("clear buffer!\n");
	ptr = inet_ntop(gethost->h_addrtype,gethost->h_addr_list[0],ip,sizeof(ip));
	//printf("right2\n");
//////////////调用Linux下ping程序得到域名下IP,显示ping结果用于对比解析结果/////////////////
	system("ping /*一个绑定固定IP域名*/ -c 2 > /home/deepin/APUE/test/.domain.log");
	file_fd=open("/home/deepin/APUE/test/.domain.log",O_RDONLY,644);
	if (file_fd < 0)
	{
		perror("open file fail!\n");
	}
	read(file_fd,buf,sizeof(buf));
	close(file_fd);
	ptrf = strstr(buf,"(");
	ptrf += 1;
	ptrb = strstr(buf,")");
	n = strlen(ptrf)-strlen(ptrb);
	strncpy(fptr,ptrf,n);
	printf("ping ip is:%s\n",fptr);
///////////////////////////////////////////////////////////////////////////////////////////////////
	return 0;
}

运行结果
在这里插入图片描述
这里得到的IP并不一样;后来分析应该是百度有多个IP的原因;
用两个IP分别进行网页登录:
在这里插入图片描述

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述发现都能正常登录百度,解析算是成功了!

猜你喜欢

转载自blog.csdn.net/qq_42425882/article/details/86763106