#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);
}
检查hostname对应ip是否为本机ip
最新推荐文章于 2023-08-09 20:08:13 发布