# UDP Sockets

## Introduction

UDP is a connection-less protocol with unreliable delivery.

## Using UDP Sockets

Incoming UDP datagrams with maximum size of 30000 bytes are supported (user code can send datagrams up to 65000 bytes). In order to receive UDP datagrams, user needs to register a handler using `Handle.Udp`:

```csharp
void Udp(UInt16 port,
         Action<IPAddress clientAddr,
         UInt16 clientPort,
         Byte[] datagram> handler)
```

* `port`: local port on which to listen for datagrams.
* `clientAddr`: represents client's IP address.
* `clientPort`: holds client port number.
* `datagram`: incoming UDP datagram.

In order to send a UDP datagram from user code, static method `UdpSocket.Send` is used:

```csharp
static void Send(IPAddress ipTo,
                 UInt16 portTo,
                 UInt16 portFrom,
                 Byte[] datagram)
```

* `ipTo`: destination IP address.
* `portTo`: destination port.
* `portFrom`: local port from which UDP datagram should be sent (usually same port on which `Handle.Udp` was called).
* `datagram`: the actual UDP datagram that should be sent.

In the following example we receive (on port 8787) and send the same echo UDP datagram back to the client:

```csharp
Handle.Udp(8787, (IPAddress clientIp, UInt16 clientPort, Byte[] datagram) =>
{    
    // One can update any resources associated with "clientIp" and "clientPort".
    UdpSocket.Send(clientIp, clientPort, 8787, datagram);
});
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.starcounter.io/2.3.1/guides/network/udp-sockets.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
