检查hostname对应ip是否为本机ip

#include <stdlib.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <vector>
#include <string>
#include <algorithm>
#include <unistd.h>
#include <cstring>

#define HOST_NAME_MAX 128
using namespace std;
bool
check_hosts (struct hostent *host, const vector<string>& ips)
{
	unsigned int cnt;
	for (cnt = 0; host->h_addr_list[cnt] != NULL; ++cnt)
	{
		char buf[INET6_ADDRSTRLEN]={0};

		const char *ip = inet_ntop (host->h_addrtype, host->h_addr_list[cnt],
							  buf, sizeof (buf));
		if(find(ips.begin(),ips.end(),string(ip)) != ips.end()){
			return true;
		};
	}
	return false;
}

bool is_local(char* hostname, const vector<string>& ips){
	int result = 0;
	struct hostent *host = NULL;
	char addr[INET6_ADDRSTRLEN]={0};

	if (inet_pton (AF_INET, hostname, &addr) || inet_pton (AF_INET6, hostname, &addr) ){
		return (find(ips.begin(),ips.end(),string(hostname)) != ips.end());
	}
	char hostname_buf[HOST_NAME_MAX]={0};
	if (gethostname(hostname_buf, HOST_NAME_MAX) == 0 && strcmp(hostname, hostname_buf) == 0){
		return true;
	}
	
	if ((host = gethostbyname2 (hostname, AF_INET)) != NULL && check_hosts(host, ips)){
		return true;
	}
	if ((host = gethostbyname2 (hostname, AF_INET6)) != NULL && check_hosts(host, ips)){
		return true;
	}
	return false;
}

int main (int argc, char* argv[]){
	vector<string> local_ips{
		"",
		"",
		""
	};
	return is_local(argv[1], local_ips);
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值