使用winsock进行p2p通信
我正在尝试使用winsock实现点对点通信,但是gethostbyaddr
总是返回NULL,这个东西只能在本地主机上工作,server_name是目标ip地址
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))
我们已经使用python实现了p2p通信,它工作得很好在相同的端口号和地址上..感谢您提供任何线索..
我不知道如何在c++中做到这一点,在python中我们只是使用bind(---),有人可以告诉我代码片段如何实现它。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您从哪里获取
server_name
?您确定这是一个有效的 IP 地址吗?另外,请检查
WSAGetLastError()
以查看具体出了什么问题。请记住,并非所有主机名都有反向 DNS 条目。
gethostbyaddr
在真实、有效的 IP 地址上失败是完全合法的。如果您正在进行 p2p,最好根本不要依赖主机名称,除非是诊断显示(如果反向查找失败,则回退到 IP 地址)。编辑:通过新的、扩展的代码示例,很明显您实际上根本不需要
gethostbyaddr
。仅当您需要相关服务器的反向 DNS 名称 时,才需要
gethostbyaddr
。inet_addr
已经为您提供了一个合适的连接地址。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.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.