UDP (also known as User Datagram Protocol) is a stateless network protocol.
Examples[]
POSIX C[]
Client[]
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#define BUFLEN 256
#define PORT 7
int main(void)
{
char buf [BUFLEN];
struct sockaddr_in si;
int sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
int flags;
si.sin_family = AF_INET;
si.sin_port = PORT; // This contains the target port number, and is adjusted.
inet_aton("127.229.133.45", &si_other.sin_addr); // COnverts target IP to network byte order. Other functions exist.
// In order:
// sockfd = socket descriptor
// buf = data buffer to send
// BUFLEN = size of data buffer.
// flags = flags used for the datagram. Supported flags include MSG_EOR and MSG_OOB.
// si = socket information defined above (contains transport endpoint)
// sizeof si = size of the socket information structure.
flags = 0;
sendto(sockfd, buf, BUFLEN, 0, &si, sizeof si)
}
This client sends a UDP packet containing the contents of the stack to a given destination. As UDP is a stateless protocol, there will be no information on whether or not the remote server received the packet, unless it replies.
Server[]
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#define BUFLEN 256
#define PORT 7
int main(void)
{
char buf [BUFLEN];
struct sockaddr_in si, si_remote;
int sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
int flags;
si.sin_family = AF_INET;
si.sin_port = PORT; // This contains the target port number, and is adjusted.
si.sin_addr.s_addr = htonl(INADDR_ANY);
bind(sockfd, &si, sizeof(si)); // Binds the inbound socket.
// In order:
// sockfd = socket descriptor
// buf = data buffer for receiving data
// BUFLEN = size of data buffer.
// flags = flags used for the datagram. Supported flags include MSG_EOR and MSG_OOB.
// si_remote = socket information for the inbound packet
// sizeof si_remove = size of the socket information structure.
//
// When a packet is received, it is
recvfrom(s, buf, BUFLEN, 0, &si_remote, sizeof(si_remote));
}