我正在尝试查找我的来源的 IP,但它不起作用。
void getSourceIp(struct hostent *sourceHost, struct ip *ipStruct)
{
char sourceName[100];
if (gethostname(sourceName,sizeof(sourceName)) < 0)
{
perror("Error in function gethostname().\n");
exit(EXIT_FAILURE);
}
if ((sourceHost = gethostbyname(sourceName)) == NULL)
{
std::cout << "The source " << sourceName << " is unknown.\n";
exit(EXIT_FAILURE);
}
ipStruct->ip_src = (*(struct in_addr *) sourceHost->h_addr_list);
std::cout << "IP Address: " << inet_ntoa(ipStruct->ip_src);
}
主功能:
int main(int argc, char *argv[])
{
struct hostent *sourceHostent = NULL;
struct hostent *destinationHostent = NULL;
struct ip *ip = NULL;
getSourceIp(sourceHostent,ip);
return 0;
}
我得到的输出是“源 macbook 未知”。