从UdpClient收到的UDP包中获取客户端IP [英] Get client IP from UDP packages received with UdpClient

查看:171
本文介绍了从UdpClient收到的UDP包中获取客户端IP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在这是给两个玩家使用的,因此一个人应该打开服务器并等待传入​​的连接.另一个播放器输入主机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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆