Consider the following program:
#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));
}
Strangely, it is printing host IP address correctly when I try to print inside printhost()
function, but giving segmentation fault when I try to print from main()
function. Can anybody please clarify?