Sending Udp Packets

From IronPython Cookbook

A simple class for sending UDP packets over a network.

This uses the System.Net.Sockets.UdpClient class.

from System.Net import IPAddress
from System.Net.Sockets import UdpClient
from System.Text import Encoding

class UdpSender(object):
    def __init__(self, port, ipAddress):
        self.client = UdpClient(0)
        # Only set this if you want to be able to listen
        # on the same machine
        self.client.MulticastLoopback = True

        # No *need* to parse - you can pass in a string
        addr = IPAddress.Parse(ipAddress)

        # Connecting means that you don't have to specify
        # The IP address when we call send.
        # For Udp, connecting isn't a requirement though
        self.client.Connect(addr, port)

    def send(self, message):
        bytearr = Encoding.UTF8.GetBytes(message)
        self.client.Send(bytearr, bytearr.Length)

To use it, you need a valid port and address. If you want to multicast, you will need a Multicast Address.

This usage example of sending does use multicast group address:

port = 5555
group = ""

udpSender = UdpSender(port, group)
udpSender.send("Some text")

In fact, because Udp is inherently a connectionless protocol, a minimal send example can be as small as:

from System.Net.Sockets import UdpClient
from System.Text import Encoding

datagram = Encoding.UTF8.GetBytes("Some text")
client = UdpClient()
client.Send(datagram, datagram.Length, hostname, port)

Note that Udp datagrams have a maximum size. See the Udp protocol for more details.

Back to Contents.