пятница, 27 августа 2010 г.

How to get UDP sender IP address and port number in .NET

Surprisingly, it was not easy to find out IP address and port number of UDP package sender in .NET. After a couple of googling hours, I gave up. The answer was found ... guess where? — At MSDN :)

So far, if you are listening some local port and accept any incoming UDP message, use EndReceiveFrom method. Below is an example of simple (and pretty useless) application, that sends a UDP message to itself (127.0.0.1).


using System;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace UDPTestProject
{
    class Program
    {
        private static byte[] buffer;
        private static Socket sender;
        private static EndPoint remoteEndPoint;
        static void Main(string[] args)
        {
            try
            {
                Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                EndPoint localEndPoint = (EndPoint)new IPEndPoint(IPAddress.Any, 30777);
                socket.Bind(localEndPoint);

                buffer = new byte[512];

                EndPoint remoteEndPoint = (EndPoint)new IPEndPoint(IPAddress.Any, 0);
                IAsyncResult ar = socket.BeginReceiveFrom(buffer,
                                        0,
                                        buffer.Length,
                                        SocketFlags.None,
                                        ref remoteEndPoint,
                                        Callback,
                                        socket);

                sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                EndPoint localhostEndPoint = (EndPoint)new IPEndPoint(IPAddress.Parse("127.0.0.1"), 30777);
                byte[] sendBuffer = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
                sender.BeginSendTo(sendBuffer, 0, sendBuffer.Length, SocketFlags.None, localhostEndPoint, OnSend, null);

                ar.AsyncWaitHandle.WaitOne();
                Console.Read();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        private static void OnSend(IAsyncResult ar)
        {
            sender.EndSend(ar);
        }

        public static void Callback(IAsyncResult ar)
        {
            Socket socket = (Socket)ar.AsyncState;
            remoteEndPoint = (EndPoint)new IPEndPoint(IPAddress.Any, 0);
            socket.EndReceiveFrom(ar, ref remoteEndPoint);
            Console.WriteLine("Received from " + remoteEndPoint.ToString());
        }
    }
}