gpt4 book ai didi

c - strlen() 拒绝从 struct hostent 读取字符串 *

转载 作者:太空宇宙 更新时间:2023-11-04 01:42:15 25 4
gpt4 key购买 nike

我一直在研究如何为 Linux 构建基本数据包嗅探器的小教程。我让一切正常,现在我想添加 IP 到主机的映射。

在我添加这个函数之前一切正常:

void IPtoHostname(char *ipaddress, char *hostname){
struct hostent *host;
in_addr_t ip = inet_addr(ipaddress);
if (!hostname){
puts("Can't allocate memory...");
exit(-1);
}
host = gethostbyaddr((char *)&ip, 32, AF_INET);
hostname = strdup(host->h_name);
}

这基本上采用字符串 IP 地址(“192.168.28.18”)ipaddress 并将该 IP 的主机名(“who.cares.com”)填入主机名

发生的事情是 strlen REFUSES 给我任何东西(我知道 strdup 是如何工作的,而且我自己测试过)并且段错误。我用过 GDB,字符串以 null 结尾字符,它不是 NULL。

我还测试了使用带有静态结构的原始字符串赋值:

void IPtoHostname(char *ipaddress, char *hostname){
static struct hostent *host;
in_addr_t ip = inet_addr(ipaddress);
if (!hostname){
puts("Can't allocate memory...");
exit(-1);
}
host = gethostbyaddr((char *)&ip, 32, AF_INET);
hostname = host->h_name;
}

仍然没有骰子。

那么,strlen 怎么了?

最佳答案

strlen 没有任何问题。您需要传入 char **hostname,然后将 *hostname 设置为 host->h_name,假设您在 IPToHostName 之外执行 strlen。您正在设置主机名指针的本地副本。

所以你有这样的东西:

char myip[]  = "123.45.67.89";
char *myhost = NULL;

IPToHostname(myip, myhost); /* this sets its own local copy of myhost, which is on the stack */

/* At this point, myhost is still null!! */

如果您将其更改为类似于下面的代码,它可能会执行您想要的操作。

void IPtoHostname(char *ipaddress, char **hostname)
{
assert(hostname); /* you'll need to include assert.h for this - it'll abort your program in debug mode if hostname is null */

struct hostent *host;
in_addr_t ip = inet_addr(ipaddress);
if (!hostname)
{
puts("Can't allocate memory...");
exit(-1);
}
host = gethostbyaddr((char *)&ip, 32, AF_INET);
*hostname = strdup(host->h_name);
}

char myip[] = "123.45.67.89";
char *myhost = NULL;

IPtoHostname(myip, &myhost);

关于c - strlen() 拒绝从 struct hostent 读取字符串 *,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3349152/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com