Browse Tag

gio

A UDP client example with GLib / GIO

Here is a simple UDP client made with GIO (GLib). GIO is a great library to use once you get up to speed on it, but sometimes I struggle to find good examples for even the most basic things, and end up building things up from scratch using the library documentation, which sometimes can be a bit tricky. So in case it is useful for someone, here it goes!

Please post any corrections.


#include <unistd.h>		/* For sleep() */
#include <string.h>		/* For strlen() */
#include <stdio.h>
#include <gio/gio.h>

int main()
{
	char *host = "127.0.0.1";
	short port = 23456;
	
	GSocket *sock;
	GSocketAddress *sock_address;
	GError *err = NULL;
	
	sock = g_socket_new(G_SOCKET_FAMILY_IPV4,
							G_SOCKET_TYPE_DATAGRAM,
							G_SOCKET_PROTOCOL_UDP,
							&err);
	
	if (err != NULL)
	{
		printf ("%s\n", err->message);
		return 1;
	}
	
	sock_address = g_inet_socket_address_new_from_string(host, port);

	while(1)
	{
		char *some_text = "Some text\n";
		g_socket_send_to(sock, sock_address, some_text, 
												strlen(some_text), NULL, &err);
		
		if (err != NULL)
		{
			printf ("%s\n", err->message);
			return 1;
		}
		
		sleep(1);
	}

	return 0;
}
Comments Off on A UDP client example with GLib / GIO