0

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?

ApprenticeHacker
  • 21,351
  • 27
  • 103
  • 153
Benyamin Jane
  • 407
  • 2
  • 5
  • 16

3 Answers3

3

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;      
}
mfontanini
  • 21,410
  • 4
  • 65
  • 73
  • vector::data is very likely not available, it's a new function in C++11 – Mahmoud Al-Qudsi Apr 15 '12 at 15:59
  • @MahmoudAl-Qudsi define "very likely not available". It's been available in GCC for some time now, and MSVC 2010 implements it. – mfontanini Apr 15 '12 at 16:08
  • It's "not available enough" to justify your calling other people's C++03 answers "awfull" [sic] (to quote you). – Mahmoud Al-Qudsi Apr 15 '12 at 16:09
  • @MahmoudAl-Qudsi okay, removed the comment. Anyway, why would you still use C++03 hacks to do what OP wanted to do, if the language already implements the exact solution to his problem? – mfontanini Apr 15 '12 at 16:13
2

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;
Ben Cottrell
  • 5,741
  • 1
  • 27
  • 34
1

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.

Israel Unterman
  • 13,158
  • 4
  • 28
  • 35