考虑以下程序:
#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));
}
奇怪的是,当我尝试在函数内部打印时,它会正确打印主机 IP 地址printhost()
,但是当我尝试从main()
函数打印时会出现分段错误。有人可以澄清一下吗?