Pass vector<char>* to function getnameinfo

282 Views Asked by At

how it is possible to pass variable of type vector* into getnameinfo function of winsock2?

GetSocketIPAndPort( struct sockaddr* ss, vector<char>* pIP, uint16_t* nPort )
{
    if (status = getnameinfo((sockaddr*)sin,sizeof(sin),pIP,sizeof(*ptr),0,0,NI_NUMERICHOST))       
    {
        return status;      
    }
}

in face it is better to ask how it is possible to convert vector* to PCHAR?

3

There are 3 best solutions below

4
On BEST ANSWER

Use the vector::data member function, which returns a pointer to the underlying array:

GetSocketIPAndPort( struct sockaddr* ss, vector<char>* pIP, uint16_t* nPort )
{
    if (status = getnameinfo((sockaddr*)sin,sizeof(sin),pIP->data(),sizeof(*ptr),0,0,NI_NUMERICHOST))       
        return status;      
}
1
On

a std::vector<char> is safely convertible into a char* by writing &my_vector[0] - e.g.

std::string fred("hello");
std::vector<char> meow(fred.begin(), fred.end());
meow.push_back('\0');
char* buffer = &meow[0];
std::cout << buffer << std::endl;
0
On

In STL it is guarantied that a vector layouts its items in consecutive memory, which you can access by taking the address of the first item, in case of vector<char> ip it is &ip[0]. The same way, for vector<char> *pIp it should be &(*pIp)[0].

You can also refer the first item using &pIp->operator[](0), but I wouldn't .. :-)

You can't, however, refer the first item using pIp->begin(), since this scheme is not guarantied to return a real address.