C#: Creating and Sending UDP Packets

I needed to test an application today that accepts UDP packets so I searched the internet for a simple program to create and send UDP packets and found a bunch of complex programs that didn’t work (or at least that I couldn’t figure out within a couple of minutes!). So, after I wasted a bunch of time I just decided to write my own method to create and send the UDP packets myself. I would have saved a ton of time had I just done this from the beginning!

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


/// <summary>
/// Sends a sepcified number of UDP packets to a host or IP Address.
/// </summary>
/// <param name="hostNameOrAddress">The host name or an IP Address to which the UDP packets will be sent.</param>
/// <param name="destinationPort">The destination port to which the UDP packets will be sent.</param>
/// <param name="data">The data to send in the UDP packet.</param>
/// <param name="count">The number of UDP packets to send.</param>
public static void SendUDPPacket(string hostNameOrAddress, int destinationPort, string data, int count)
    // Validate the destination port number
    if (destinationPort < 1 || destinationPort > 65535)
        throw new ArgumentOutOfRangeException("destinationPort", "Parameter destinationPort must be between 1 and 65,535.");

    // Resolve the host name to an IP Address
    IPAddress[] ipAddresses = Dns.GetHostAddresses(hostNameOrAddress);
    if (ipAddresses.Length == 0)
        throw new ArgumentException("Host name or address could not be resolved.", "hostNameOrAddress");

    // Use the first IP Address in the list
    IPAddress destination = ipAddresses[0];            
    IPEndPoint endPoint = new IPEndPoint(destination, destinationPort);
    byte[] buffer = Encoding.ASCII.GetBytes(data);

    // Send the packets
    Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);           
    for(int i = 0; i < count; i++)
        socket.SendTo(buffer, endPoint);

Update: So, it turns out that the .NET Framework actually already has a class for sending UDP packets called UdpClient. The documentation for it can be found here. It definitely provides a lot more options but if you are looking for a simple method, the above works too!


2 Responses to “C#: Creating and Sending UDP Packets”

  1. Sam Says:

    Awesome code
    Thanks brother 🙂

  2. Sam Says:

    code for Creating and receiving UDP packets?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: