【发布时间】:2015-09-11 07:35:49
【问题描述】:
考虑以下程序:
#include <sys/socket.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <netdb.h>
void printhost(char* pLocalHostAddress )
{
struct hostent * pHost;
struct in_addr **pptr;
char hostName[128]="\0";
gethostname(hostName, sizeof(hostName));
printf("%s",hostName);
if( NULL != (pHost = gethostbyname(hostName)) )
{
memcpy( pLocalHostAddress, *pHost->h_addr_list, 4);
printf("ip address: %s\n",inet_ntoa(**(struct in_addr **)&pLocalHostAddress));
}
}
void main()
{
char pLocalHostAddress[50];
printhost((char *)pLocalHostAddress);
printf("ip address: %s\n",inet_ntoa(**(struct in_addr **)&pLocalHostAddress));
}
奇怪的是,当我尝试在printhost() 函数中打印时,它正在正确打印主机 IP 地址,但是当我尝试从 main() 函数中打印时出现分段错误。有人可以澄清一下吗?
【问题讨论】:
-
**(struct in_addr **)&pLocalHostAddress)- 到底是什么 -
我已经删除了 c++ :)
-
数组自然衰减为指针(指向第一个元素),您无需将数组强制转换为指针。
-
顺便说一句,您的代码中有两个不同的变量,都名为
pLocalHostAddress。他们有不同的地址,所以你不应该期望通过别名地址得到相同的结果 -
正如@M.M 所说,到底是什么。您是否看过 inet_ntoa 的手册页?
标签: c sockets host gethostbyname