glib-integration.c
Example of how to integrate avahi use with GLIB/GTK applications
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <glib.h>
#include <avahi-client/client.h>
#include <avahi-common/error.h>
#include <avahi-common/timeval.h>
#include <avahi-glib/glib-watch.h>
#include <avahi-glib/glib-malloc.h>
static void
avahi_timeout_event (AVAHI_GCC_UNUSED AvahiTimeout *timeout, AVAHI_GCC_UNUSED void *userdata)
{
g_message ("Avahi API Timeout reached!");
}
static gboolean
avahi_timeout_event_glib (void *userdata)
{
GMainLoop *loop = userdata;
g_message ("GLIB API Timeout reached, quitting main loop!");
g_main_loop_quit (loop);
return FALSE;
}
static void
avahi_client_callback (AVAHI_GCC_UNUSED AvahiClient *client, AvahiClientState state, void *userdata)
{
GMainLoop *loop = userdata;
g_message ("Avahi Client State Change: %d", state);
if (state == AVAHI_CLIENT_FAILURE)
{
g_message ("Disconnected from the Avahi Daemon: %s", avahi_strerror(avahi_client_errno(client)));
g_main_loop_quit (loop);
}
}
int
main (AVAHI_GCC_UNUSED int argc, AVAHI_GCC_UNUSED char *argv[])
{
GMainLoop *loop = NULL;
const AvahiPoll *poll_api;
AvahiGLibPoll *glib_poll;
AvahiClient *client;
struct timeval tv;
const char *version;
int error;
avahi_set_allocator (avahi_glib_allocator ());
loop = g_main_loop_new (NULL, FALSE);
glib_poll = avahi_glib_poll_new (NULL, G_PRIORITY_DEFAULT);
poll_api = avahi_glib_poll_get (glib_poll);
avahi_elapse_time (&tv,
1000,
0);
poll_api->timeout_new (poll_api,
&tv,
avahi_timeout_event,
NULL);
g_timeout_add (5000,
avahi_timeout_event_glib,
loop);
client = avahi_client_new (poll_api,
0,
avahi_client_callback,
loop,
&error);
if (client == NULL)
{
g_warning ("Error initializing Avahi: %s", avahi_strerror (error));
goto fail;
}
version = avahi_client_get_version_string (client);
if (version == NULL)
{
g_warning ("Error getting version string: %s", avahi_strerror (avahi_client_errno (client)));
goto fail;
}
g_message ("Avahi Server Version: %s", version);
g_main_loop_run (loop);
fail:
g_main_loop_unref (loop);
avahi_client_free (client);
avahi_glib_poll_free (glib_poll);
return 0;
}