Hi,
I have created a basic function which returns all the ip addresses when you pass in the name of the server and port number. My question is, is the code safe?
sIpAddress is created on the stack, and then assigned the ip from the return of the inet_ntoa function. This string is then pushed onto the list. However, as far I as i am aware, the list probaly uses ptrs to the type of object it is pointing to. So after this function returns, wont the memory created within the stack frame be destroyed?, i.e. string sIpAddress.....
The function actually works, and returns three ip addresses if you pass in www.google.com. The results were:
66.102.9.104
66.102.9.99
66.102.9.147
Any advice welcome, thanks.
Code:list <string> GetHostIp(string sName, string sPort) { list <string> listHostAddresses; string sIpAddress; addrinfo aiHints; addrinfo *aiList = NULL; sockaddr_in *hostinfo; memset(&aiHints, 0, sizeof(aiHints)); aiHints.ai_family = AF_INET; aiHints.ai_socktype = SOCK_STREAM; aiHints.ai_protocol = IPPROTO_TCP; if(getaddrinfo(sName.c_str(), sPort.c_str(), &aiHints, &aiList)) ProcessError(ERR_IP_ADDRESS, false); for(addrinfo *i = aiList; i; i = i->ai_next) { hostinfo = (sockaddr_in *)i->ai_addr; sIpAddress = string(inet_ntoa(hostinfo->sin_addr)); listHostAddresses.push_back(sIpAddress); } return listHostAddresses; }