次のプログラムを検討してください。
#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()
ます。誰でも明確にできますか?