当前位置:  开发笔记 > 编程语言 > 正文

从UDP连接C#获取客户端IP

如何解决《从UDP连接C#获取客户端IP》经验,为你挑选了1个好方法。

我目前有一个服务器应用程序正在侦听UDP数据包的端口.当一个发送到服务器时,它会正确接收并处理它.有什么方法可以得到数据包来自哪里的IP地址?

这是我创建套接字的方法

this.UDPListener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, Port);
this.UDPListener.Bind(endPoint);

SocketAsyncEventArgs socketEventArgs = new SocketAsyncEventArgs(); 
socketEventArgs.SetBuffer(this.ReceiveBuffer, 0, this.ReceiveBuffer.Length);
socketEventArgs.Completed += new EventHandler(OnReceive);
if (!this.UDPListener.ReceiveAsync(socketEventArgs))
    ThreadPool.QueueUserWorkItem(new WaitCallback((Object o) => this.OnReceive(this, socketEventArgs)));

当调用OnReceive时,没有任何内容包含消息来自的ip.我已经查看了SocketAsyncEventArgs,我看到的只是监听ip.

编辑:

这就是我最终做的事情.

this.UDPListener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
this.UDPListener.Bind(new IPEndPoint(IPAddress.Any, Port));

EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
this.UDPListener.BeginReceiveFrom(ReceiveBuffer, 0, ReceiveBuffer.Length, SocketFlags.None, ref remoteEndPoint, OnReceive, this.UDPListener);

然后在OnReceive继承人如何获取数据和信息

//Get the received message.
Socket receiveSocket = (Socket)AsyncResult.AsyncState;
EndPoint clientEndPoint = new IPEndPoint(IPAddress.Any, 0);
int udpMessageLength = receiveSocket.EndReceiveFrom(AsyncResult, ref clientEndPoint);
byte[] udpMessage = new byte[udpMessageLength];
Array.Copy(ReceiveBuffer, udpMessage, udpMessageLength);

//Start listening for a new message.
EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, Int32.Parse(((IPEndPoint)receiveSocket.LocalEndPoint).Port.ToString()));
this.UDPListener.BeginReceiveFrom(ReceiveBuffer, 0, ReceiveBuffer.Length, SocketFlags.None, ref remoteEndPoint, OnReceive, this.UDPListener);

//Handle the received message
Debug.WriteLine("Recieved {0} bytes from {1}:{2} to {3}:{4}", udpMessageLength, ((IPEndPoint)clientEndPoint).Address, ((IPEndPoint)clientEndPoint).Port, ((IPEndPoint)receiveSocket.LocalEndPoint).Address, ((IPEndPoint)receiveSocket.LocalEndPoint).Port);

Allon Guraln.. 6

我不知道UdpClient,但是如果Socket直接使用该类,则可以调用该.ReceiveFrom(byte[], ref EndPoint)方法,并通过第二个参数接收远程地址.



1> Allon Guraln..:

我不知道UdpClient,但是如果Socket直接使用该类,则可以调用该.ReceiveFrom(byte[], ref EndPoint)方法,并通过第二个参数接收远程地址.

推荐阅读
echo7111436
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有