Thursday, 15 August 2013

c++ - Why does getpeername() return OK yet the result is not as expected? -



c++ - Why does getpeername() return OK yet the result is not as expected? -

the problem has been resolved. root cause passed c++ temporary object sockaddr* of getpeername(), automatically destroyed after getpeername() returned.

therefore, net result total of 0s.

sorry carelessness. i've voted close post. please vote close, too.

#include <winsock2.h> #include <windows.h> #include <thread> using namespace std; void server() { sockaddr_in server_addr {}; server_addr.sin_family = af_inet; server_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); server_addr.sin_port = htons(1234); socket s_listening = socket(af_inet, sock_stream, 0); bind(s_listening, (sockaddr*)&server_addr, sizeof(server_addr)); listen(s_listening, 5); while (true) { auto s_new = accept(s_listening, 0, 0); sockaddr_in client_addr {}; int size = sizeof(client_addr); auto ret = getpeername(s_new, (sockaddr*)&client_addr, &size); // // ret 0, means phone call getpeername ok. // client_addr total of 0s rather "127.0.0.1:4". why? // } } int main() { std::thread(server).detach(); socket s_client = socket(af_inet, sock_stream, 0); sockaddr_in client_addr {}; client_addr.sin_family = af_inet; client_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); client_addr.sin_port = htons(4); bind(s_client, (sockaddr*)&client_addr, sizeof(client_addr)); sockaddr_in server_addr {}; server_addr.sin_family = af_inet; server_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); server_addr.sin_port = htons(1234); connect(s_client, (sockaddr*)&server_addr, sizeof(server_addr)); getchar(); }

the code compiled vc++ 2012. however, although phone call function getpeername returns ok, returned info wrong (full of 0s), why?

getpeername() initialises sockaddr_<something> structure. if <something> equals in holding ip-address , port in binary format.

it not carry character buffer holding ascii representation of peer's name/address , port.

also values in sockaddr_in held in network bytes order.

to print address , port expressed comment in op's source snippet, can follows:

#include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> ... int sd = -1; /* init invalid socket */ ... /* sd proper value */ sockaddr_in sa = {0}; /* init zeros */ socklen_t sl = sizeof(sa); if (getpeername(sd, (sockaddr *) &sa, &sl)) perror("getpeername() failed"); else printf("peer is: %s:%hu\n", inetntoa(sa.sinaddr), ntohs(sa.sin_port));

c++ sockets networking tcp

No comments:

Post a Comment