不同网络的两台机器之间的 WinSock 连接出错 C

发布于 2025-01-10 06:27:48 字数 805 浏览 0 评论 0原文

我制作了一个服务器/客户端程序,当我在同一网络或同一台机器上建立连接时,一切正常。然而,这是我的问题:当我断开客户端计算机与本地网络的连接并将其连接到另一个网络(wifi)时,它不会连接到服务器。

这是我的服务器的一部分:

        ZeroMemory(&hints, sizeof(hints));
        hints.ai_family = AF_INET;
        hints.ai_socktype = SOCK_STREAM;
        hints.ai_protocol = IPPROTO_TCP;
        hints.ai_flags = AI_PASSIVE;

        res = getaddrinfo(NULL, PORT, &hints, &result);

客户端:

        ZeroMemory(&hints, sizeof(hints));
        hints.ai_family = AF_INET;
        hints.ai_socktype = SOCK_STREAM;
        hints.ai_protocol = IPPROTO_TCP;

        res = getaddrinfo(SERVER_HOST, PORT, &hints, &result);

我的客户端代码中的目标端口与我的服务器中的端口相同。我在某处读到我必须购买唯一的 IP 地址?所以我的问题是:如何使用 C (WinSock) 中的套接字连接不同网络上的两台计算机?

I made a server/client program, everything works fine when I make a connection on the same network or on the same machine. This is however my problem: when I disconnect the client machine from the local network and connect it to another network(wifi) it doesn't connect to the server.

This is a part of my server:

        ZeroMemory(&hints, sizeof(hints));
        hints.ai_family = AF_INET;
        hints.ai_socktype = SOCK_STREAM;
        hints.ai_protocol = IPPROTO_TCP;
        hints.ai_flags = AI_PASSIVE;

        res = getaddrinfo(NULL, PORT, &hints, &result);

Client:

        ZeroMemory(&hints, sizeof(hints));
        hints.ai_family = AF_INET;
        hints.ai_socktype = SOCK_STREAM;
        hints.ai_protocol = IPPROTO_TCP;

        res = getaddrinfo(SERVER_HOST, PORT, &hints, &result);

The destination port in my client code is the same port as the one in my server. I read somewhere that I have to buy a unique IP address? So my question is: How can I connect two computers on different networks using sockets in C (WinSock)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

巷子口的你 2025-01-17 06:27:48

好吧,我发现我的路由器需要端口转发。刚刚联系了我的网络提供商,因为我无法选择制定新的“端口转发规则”。我在路由器配置中制定了一条新规则。我将我的私有(内部)IP 地址和我在服务器/客户端程序中使用的端口号放入新规则中。 这是一个很好的资源

Okay, I figured out that I need port forwarding on my router. Just contacted my network provider because I didn't had the option to make a new 'port forward rule'. I made a new rule in my router configuration. I put my private (internal) ip address into the new rule with a port number that I use in my server/client program. This is a nice resource.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文