Rahul K wrote:
Quote:
Hi
>
I am working on Visual Studio on Windows. I have a function which
return the list of all the IP Addresses of a machine:
>
vector<char *getAllLocalIPAddress()
{
char localHostName[MAX_HOSTNAME_LENGTH];
struct hostent *hp;
int i=0,rc;
vector<char *allLocalIP;
>
/* Get the local hostname */
rc = getLocalHostName(localHostName, MAX_HOSTNAME_LENGTH); //This is
my function to get local hostname. Assume that it works fine
>
/* If getLocalHostName() failed */
if(rc != 0)
return allLocalIP;
>
#ifdef WIN32
/* Initiate wsock32.dll */
int success = utilWSAStartup(); //This is my function to initialize
wsock32.dll Lets assume that it is successful
>
/* The WinSock DLL is acceptable. Proceed. */
if(success == 0)
/* Get host information corresponding to local host */
hp = gethostbyname(localHostName);
>
WSACleanup();
#else
hp = gethostbyname(localHostName);
#endif
>
if(hp == NULL)
return allLocalIP ;
>
/*Push all the Local IP Addresses in the vector */
while(hp->h_addr_list[i] != NULL)
{
cout << "Inside while loop";
allLocalIP.push_back(inet_ntoa(*(struct in_addr
*)(hp->h_addr_list[i])));
i++;
}
>
/*Return the vector containing all the Local IP Address */
cout << "Outputting all local IP addresses inside function itself\n";
for(i=0 ;i<allLocalIP.size(); i++)
cout << allLocalIP[i] << "\n";
>
/*Return the vector containing all the Local IP Address */
return allLocalIP;
}
>
This function is in a DLL .
As can be seen, I am printing all the IP Addresses inside function
itself also. This is working fine and printing IP addresses well.
>
When i write a application and link it to this DLL, I make the call as
follows;
>
vector<char *localIP;
localIP = getAllLocalIPAddress();
>
At this point when the function return and try to assign the return
value to vector localIP, it gives error something like this:
The function inet_ntoa returns a pointer to an internal buffer. This
buffer is only valid until the next call to this function (or maybe even
less than that, I'm not sure). Do you really see all _different_ ip
addresses on your debug output before returning? I'd suspect that they
are all the last IP address.
Try replacing the string holding array to type
vector< std::string >
Then the string will be copied in it's own buffer.
Use std::string as often as you can, raw pointers are error prone.
Jens