Skip to content
Snippets Groups Projects
Commit 7f8af790 authored by Bruce Cowan's avatar Bruce Cowan :airplane:
Browse files

Add POSIX UDP server example

parent 8a292082
No related branches found
No related tags found
No related merge requests found
Pipeline #2333 passed
......@@ -43,3 +43,7 @@ endif
if thread_dep.found()
subdir('pthread')
endif
if host_machine.system() != 'windows'
subdir('posix')
endif
executable('udp-server', 'udp-server.c')
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#define PORT 46123
#define BUF_LENGTH 1024
int
main (void)
{
int sock = socket (AF_INET, SOCK_DGRAM, 0);
if (sock == -1)
{
perror ("socket");
exit (EXIT_FAILURE);
}
struct sockaddr_in addr;
memset (&addr, 0, sizeof (struct sockaddr_in));
addr.sin_family = AF_INET;
addr.sin_port = htons (PORT);
addr.sin_addr.s_addr = htonl (INADDR_ANY);
if (bind (sock, (struct sockaddr *) &addr, sizeof (addr)) == -1)
{
perror ("bind");
close (sock);
exit (EXIT_FAILURE);
}
while (true)
{
char buf[BUF_LENGTH];
struct sockaddr_in src_addr;
socklen_t addrlen = sizeof (struct sockaddr_in);
char str[INET_ADDRSTRLEN];
ssize_t bytes = recvfrom (sock, buf, BUF_LENGTH, 0,
(struct sockaddr *) &src_addr, &addrlen);
if (inet_ntop (AF_INET, &src_addr.sin_addr, str, INET_ADDRSTRLEN) == NULL)
{
fprintf (stderr, "Could not convert address to string\n");
exit (EXIT_FAILURE);
}
printf ("Received %zd bytes from %s\n", bytes, str);
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment