tags:

views:

159

answers:

1

I am trying to achieve peer to peer communication using winsock but gethostbyaddr always return me NULL ,this thing works only on localhost, server_name is destination ip address

server_name="<--ipaddress-->"

struct sockaddr_in server;
addr = inet_addr(server_name);
cout<<"inet_addr(server_name) "<<addr<<endl;
hp = gethostbyaddr((char *)&addr, 4, AF_INET);
memset(&server, 0, sizeof(server));


memcpy(&(server.sin_addr), hp->h_addr, hp->h_length);
server.sin_family = hp->h_addrtype;
server.sin_port = htons(port);
conn_socket = socket(AF_INET, socket_type, 0); 

connect(conn_socket, (struct sockaddr*)&server, sizeof(server))

We have already achieved p2p communication using python and it works perfectly fine on same port no and address .. thanks for any clue..

I do not have any idea how to do it in c++, in python we just used bind(---) , Can somebody show me code snippet how to achieve it.

A: 

Where are you getting server_name from? Are you sure it's a valid IP address? Also, check WSAGetLastError() to see specifically what's going wrong.

Remember that not all hostnames have reverse DNS entries. It's perfectly legitimate for gethostbyaddr to fail on a real, valid IP address. If you're doing p2p, it's best not to rely on host names at all, except perhaps for diagnostic displays (and fall back to IP addresses if reverse lookups fail).

Edit: With your new, expanded code sample, it's clear that you actually don't need gethostbyaddr at all.

struct sockaddr_in server;
memset((void*)&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_addr.S_un.S_long = inet_addr(server_name);
server.sin_port = htons(port);
conn_socket = socket(AF_INET, socket_type, 0); 

connect(conn_socket, (struct sockaddr*)&server, sizeof(server))

gethostbyaddr is only needed when you need the reverse DNS name of the server in question. inet_addr already gives you a suitable address to connect to.

bdonlan