从使用 UdpClient 接收的 UDP 包中获取客户端 IP

Get client IP from UDP packages received with UdpClient(从使用 UdpClient 接收的 UDP 包中获取客户端 IP)
本文介绍了从使用 UdpClient 接收的 UDP 包中获取客户端 IP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 System.Net.Sockets.UdpClient 类.

这是两个玩家,所以一个人应该打开一个服务器并等待传入​​的连接.另一个玩家输入主机 IP 并尝试发送ping",以确保连接是可能的并且有一个打开的服务器.然后主机以pong"响应.

It's for two players, so one should open a server and wait for incoming connections. The other player inputs the host IP and tries to send a "ping", to make sure a connection is possible and there is an open server. The host then responds with a "pong".

游戏运行后,双方都要互相发送udp消息,所以都需要对方的ip地址.

Once the game is running, both have to send udp messages to each other, so they both need the opponents ip address.

当然服务器也可以输入客户端的IP,不过我觉得没必要.

Of course the server could also input the clients IP, but that seems unneccessary to me.

收到ping"消息后,如何从 udp 包中获取客户端 IP?

How can I get the clients IP from the udp package when the "ping" message is received?

这是我的接收代码(服务器等待 ping):

Here is my receiving code (server waiting for ping):

    private void ListenForPing()
    {
        while (!closeEverything)
        {
             var deserializer = new ASCIIEncoding();
             IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
             byte[] recData = udp.Receive(ref anyIP);
             string ping = deserializer.GetString(recData);
             if (ping == "ping")
             {
                 Console.WriteLine("Ping received.");
                 InvokePingReceiveEvent();
             }
        }
    }

推荐答案

在您的示例中,当客户端连接时,anyIP IPEndPoint 对象将包含客户端连接的地址和端口.

In your example, when a client connects, the anyIP IPEndPoint object will contain the address and port of the client connection.

这篇关于从使用 UdpClient 接收的 UDP 包中获取客户端 IP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)