1 /* GIO - GLib Input, Output and Streaming Library
3 * Copyright © 2008 Christian Kellner, Samuel Cormier-Iijima
4 * Copyright © 2009 codethink
5 * Copyright © 2009 Red Hat, Inc
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General
18 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
20 * Authors: Christian Kellner <gicmo@gnome.org>
21 * Samuel Cormier-Iijima <sciyoshi@gmail.com>
22 * Ryan Lortie <desrt@desrt.ca>
23 * Alexander Larsson <alexl@redhat.com>
27 #include "gsocketlistener.h"
29 #include <gio/gioenumtypes.h>
30 #include <gio/gtask.h>
31 #include <gio/gcancellable.h>
32 #include <gio/gsocketaddress.h>
33 #include <gio/ginetaddress.h>
34 #include <gio/gioerror.h>
35 #include <gio/gsocket.h>
36 #include <gio/gsocketconnection.h>
37 #include <gio/ginetsocketaddress.h>
39 #include "gmarshal-internal.h"
43 * SECTION:gsocketlistener
44 * @title: GSocketListener
45 * @short_description: Helper for accepting network client connections
47 * @see_also: #GThreadedSocketService, #GSocketService.
49 * A #GSocketListener is an object that keeps track of a set
50 * of server sockets and helps you accept sockets from any of the
51 * socket, either sync or async.
53 * Add addresses and ports to listen on using g_socket_listener_add_address()
54 * and g_socket_listener_add_inet_port(). These will be listened on until
55 * g_socket_listener_close() is called. Dropping your final reference to the
56 * #GSocketListener will not cause g_socket_listener_close() to be called
57 * implicitly, as some references to the #GSocketListener may be held
60 * If you want to implement a network server, also look at #GSocketService
61 * and #GThreadedSocketService which are subclasses of #GSocketListener
62 * that make this even easier.
79 static guint signals[LAST_SIGNAL] = { 0 };
81 static GQuark source_quark = 0;
83 struct _GSocketListenerPrivate
86 GMainContext *main_context;
91 G_DEFINE_TYPE_WITH_PRIVATE (GSocketListener, g_socket_listener, G_TYPE_OBJECT)
94 g_socket_listener_finalize (GObject *object)
96 GSocketListener *listener = G_SOCKET_LISTENER (object);
98 if (listener->priv->main_context)
99 g_main_context_unref (listener->priv->main_context);
101 /* Do not explicitly close the sockets. Instead, let them close themselves if
102 * their final reference is dropped, but keep them open if a reference is
103 * held externally to the GSocketListener (which is possible if
104 * g_socket_listener_add_socket() was used).
106 g_ptr_array_free (listener->priv->sockets, TRUE);
108 G_OBJECT_CLASS (g_socket_listener_parent_class)
113 g_socket_listener_get_property (GObject *object,
118 GSocketListener *listener = G_SOCKET_LISTENER (object);
122 case PROP_LISTEN_BACKLOG:
123 g_value_set_int (value, listener->priv->listen_backlog);
127 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
132 g_socket_listener_set_property (GObject *object,
137 GSocketListener *listener = G_SOCKET_LISTENER (object);
141 case PROP_LISTEN_BACKLOG:
142 g_socket_listener_set_backlog (listener, g_value_get_int (value));
146 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
151 g_socket_listener_class_init (GSocketListenerClass *klass)
153 GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
155 gobject_class->finalize = g_socket_listener_finalize;
156 gobject_class->set_property = g_socket_listener_set_property;
157 gobject_class->get_property = g_socket_listener_get_property;
158 g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
159 g_param_spec_int ("listen-backlog",
160 P_("Listen backlog"),
161 P_("outstanding connections in the listen queue"),
165 G_PARAM_CONSTRUCT | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
168 * GSocketListener::event:
169 * @listener: the #GSocketListener
170 * @event: the event that is occurring
171 * @socket: the #GSocket the event is occurring on
173 * Emitted when @listener's activity on @socket changes state.
174 * Note that when @listener is used to listen on both IPv4 and
175 * IPv6, a separate set of signals will be emitted for each, and
176 * the order they happen in is undefined.
181 g_signal_new (I_("event"),
182 G_TYPE_FROM_CLASS (gobject_class),
184 G_STRUCT_OFFSET (GSocketListenerClass, event),
186 _g_cclosure_marshal_VOID__ENUM_OBJECT,
188 G_TYPE_SOCKET_LISTENER_EVENT,
190 g_signal_set_va_marshaller (signals[EVENT],
191 G_TYPE_FROM_CLASS (gobject_class),
192 _g_cclosure_marshal_VOID__ENUM_OBJECTv);
194 source_quark = g_quark_from_static_string ("g-socket-listener-source");
198 g_socket_listener_init (GSocketListener *listener)
200 listener->priv = g_socket_listener_get_instance_private (listener);
201 listener->priv->sockets =
202 g_ptr_array_new_with_free_func ((GDestroyNotify) g_object_unref);
203 listener->priv->listen_backlog = 10;
207 * g_socket_listener_new:
209 * Creates a new #GSocketListener with no sockets to listen for.
210 * New listeners can be added with e.g. g_socket_listener_add_address()
211 * or g_socket_listener_add_inet_port().
213 * Returns: a new #GSocketListener.
218 g_socket_listener_new (void)
220 return g_object_new (G_TYPE_SOCKET_LISTENER, NULL);
224 check_listener (GSocketListener *listener,
227 if (listener->priv->closed)
229 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
230 _("Listener is already closed"));
238 * g_socket_listener_add_socket:
239 * @listener: a #GSocketListener
240 * @socket: a listening #GSocket
241 * @source_object: (nullable): Optional #GObject identifying this source
242 * @error: #GError for error reporting, or %NULL to ignore.
244 * Adds @socket to the set of sockets that we try to accept
245 * new clients from. The socket must be bound to a local
246 * address and listened to.
248 * @source_object will be passed out in the various calls
249 * to accept to identify this particular source, which is
250 * useful if you're listening on multiple addresses and do
251 * different things depending on what address is connected to.
253 * The @socket will not be automatically closed when the @listener is finalized
254 * unless the listener held the final reference to the socket. Before GLib 2.42,
255 * the @socket was automatically closed on finalization of the @listener, even
256 * if references to it were held elsewhere.
258 * Returns: %TRUE on success, %FALSE on error.
263 g_socket_listener_add_socket (GSocketListener *listener,
265 GObject *source_object,
268 if (!check_listener (listener, error))
271 /* TODO: Check that socket it is bound & not closed? */
273 if (g_socket_is_closed (socket))
275 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
276 _("Added socket is closed"));
280 g_object_ref (socket);
281 g_ptr_array_add (listener->priv->sockets, socket);
284 g_object_set_qdata_full (G_OBJECT (socket), source_quark,
285 g_object_ref (source_object), g_object_unref);
288 if (G_SOCKET_LISTENER_GET_CLASS (listener)->changed)
289 G_SOCKET_LISTENER_GET_CLASS (listener)->changed (listener);
295 * g_socket_listener_add_address:
296 * @listener: a #GSocketListener
297 * @address: a #GSocketAddress
298 * @type: a #GSocketType
299 * @protocol: a #GSocketProtocol
300 * @source_object: (nullable): Optional #GObject identifying this source
301 * @effective_address: (out) (optional): location to store the address that was bound to, or %NULL.
302 * @error: #GError for error reporting, or %NULL to ignore.
304 * Creates a socket of type @type and protocol @protocol, binds
305 * it to @address and adds it to the set of sockets we're accepting
308 * Note that adding an IPv6 address, depending on the platform,
309 * may or may not result in a listener that also accepts IPv4
310 * connections. For more deterministic behavior, see
311 * g_socket_listener_add_inet_port().
313 * @source_object will be passed out in the various calls
314 * to accept to identify this particular source, which is
315 * useful if you're listening on multiple addresses and do
316 * different things depending on what address is connected to.
318 * If successful and @effective_address is non-%NULL then it will
319 * be set to the address that the binding actually occurred at. This
320 * is helpful for determining the port number that was used for when
321 * requesting a binding to port 0 (ie: "any port"). This address, if
322 * requested, belongs to the caller and must be freed.
324 * Call g_socket_listener_close() to stop listening on @address; this will not
325 * be done automatically when you drop your final reference to @listener, as
326 * references may be held internally.
328 * Returns: %TRUE on success, %FALSE on error.
333 g_socket_listener_add_address (GSocketListener *listener,
334 GSocketAddress *address,
336 GSocketProtocol protocol,
337 GObject *source_object,
338 GSocketAddress **effective_address,
341 GSocketAddress *local_address;
342 GSocketFamily family;
345 if (!check_listener (listener, error))
348 family = g_socket_address_get_family (address);
349 socket = g_socket_new (family, type, protocol, error);
353 g_socket_set_listen_backlog (socket, listener->priv->listen_backlog);
355 g_signal_emit (listener, signals[EVENT], 0,
356 G_SOCKET_LISTENER_BINDING, socket);
358 if (!g_socket_bind (socket, address, TRUE, error))
360 g_object_unref (socket);
364 g_signal_emit (listener, signals[EVENT], 0,
365 G_SOCKET_LISTENER_BOUND, socket);
366 g_signal_emit (listener, signals[EVENT], 0,
367 G_SOCKET_LISTENER_LISTENING, socket);
369 if (!g_socket_listen (socket, error))
371 g_object_unref (socket);
375 g_signal_emit (listener, signals[EVENT], 0,
376 G_SOCKET_LISTENER_LISTENED, socket);
378 local_address = NULL;
379 if (effective_address)
381 local_address = g_socket_get_local_address (socket, error);
382 if (local_address == NULL)
384 g_object_unref (socket);
389 if (!g_socket_listener_add_socket (listener, socket,
394 g_object_unref (local_address);
395 g_object_unref (socket);
399 if (effective_address)
400 *effective_address = local_address;
402 g_object_unref (socket); /* add_socket refs this */
408 * g_socket_listener_add_inet_port:
409 * @listener: a #GSocketListener
410 * @port: an IP port number (non-zero)
411 * @source_object: (nullable): Optional #GObject identifying this source
412 * @error: #GError for error reporting, or %NULL to ignore.
414 * Helper function for g_socket_listener_add_address() that
415 * creates a TCP/IP socket listening on IPv4 and IPv6 (if
416 * supported) on the specified port on all interfaces.
418 * @source_object will be passed out in the various calls
419 * to accept to identify this particular source, which is
420 * useful if you're listening on multiple addresses and do
421 * different things depending on what address is connected to.
423 * Call g_socket_listener_close() to stop listening on @port; this will not
424 * be done automatically when you drop your final reference to @listener, as
425 * references may be held internally.
427 * Returns: %TRUE on success, %FALSE on error.
432 g_socket_listener_add_inet_port (GSocketListener *listener,
434 GObject *source_object,
437 gboolean need_ipv4_socket = TRUE;
438 GSocket *socket4 = NULL;
441 g_return_val_if_fail (listener != NULL, FALSE);
442 g_return_val_if_fail (port != 0, FALSE);
444 if (!check_listener (listener, error))
447 /* first try to create an IPv6 socket */
448 socket6 = g_socket_new (G_SOCKET_FAMILY_IPV6,
449 G_SOCKET_TYPE_STREAM,
450 G_SOCKET_PROTOCOL_DEFAULT,
454 /* IPv6 is supported on this platform, so if we fail now it is
455 * a result of being unable to bind to our port. Don't fail
456 * silently as a result of this!
459 GInetAddress *inet_address;
460 GSocketAddress *address;
462 inet_address = g_inet_address_new_any (G_SOCKET_FAMILY_IPV6);
463 address = g_inet_socket_address_new (inet_address, port);
464 g_object_unref (inet_address);
466 g_socket_set_listen_backlog (socket6, listener->priv->listen_backlog);
468 g_signal_emit (listener, signals[EVENT], 0,
469 G_SOCKET_LISTENER_BINDING, socket6);
471 if (!g_socket_bind (socket6, address, TRUE, error))
473 g_object_unref (address);
474 g_object_unref (socket6);
478 g_object_unref (address);
480 g_signal_emit (listener, signals[EVENT], 0,
481 G_SOCKET_LISTENER_BOUND, socket6);
482 g_signal_emit (listener, signals[EVENT], 0,
483 G_SOCKET_LISTENER_LISTENING, socket6);
485 if (!g_socket_listen (socket6, error))
487 g_object_unref (socket6);
491 g_signal_emit (listener, signals[EVENT], 0,
492 G_SOCKET_LISTENER_LISTENED, socket6);
495 g_object_set_qdata_full (G_OBJECT (socket6), source_quark,
496 g_object_ref (source_object),
499 /* If this socket already speaks IPv4 then we are done. */
500 if (g_socket_speaks_ipv4 (socket6))
501 need_ipv4_socket = FALSE;
504 if (need_ipv4_socket)
505 /* We are here for exactly one of the following reasons:
507 * - our platform doesn't support IPv6
508 * - we successfully created an IPv6 socket but it's V6ONLY
510 * In either case, we need to go ahead and create an IPv4 socket
511 * and fail the call if we can't bind to it.
514 socket4 = g_socket_new (G_SOCKET_FAMILY_IPV4,
515 G_SOCKET_TYPE_STREAM,
516 G_SOCKET_PROTOCOL_DEFAULT,
520 /* IPv4 is supported on this platform, so if we fail now it is
521 * a result of being unable to bind to our port. Don't fail
522 * silently as a result of this!
525 GInetAddress *inet_address;
526 GSocketAddress *address;
528 inet_address = g_inet_address_new_any (G_SOCKET_FAMILY_IPV4);
529 address = g_inet_socket_address_new (inet_address, port);
530 g_object_unref (inet_address);
532 g_socket_set_listen_backlog (socket4,
533 listener->priv->listen_backlog);
535 g_signal_emit (listener, signals[EVENT], 0,
536 G_SOCKET_LISTENER_BINDING, socket4);
538 if (!g_socket_bind (socket4, address, TRUE, error))
540 g_object_unref (address);
541 g_object_unref (socket4);
543 g_object_unref (socket6);
548 g_object_unref (address);
550 g_signal_emit (listener, signals[EVENT], 0,
551 G_SOCKET_LISTENER_BOUND, socket4);
552 g_signal_emit (listener, signals[EVENT], 0,
553 G_SOCKET_LISTENER_LISTENING, socket4);
555 if (!g_socket_listen (socket4, error))
557 g_object_unref (socket4);
559 g_object_unref (socket6);
564 g_signal_emit (listener, signals[EVENT], 0,
565 G_SOCKET_LISTENER_LISTENED, socket4);
568 g_object_set_qdata_full (G_OBJECT (socket4), source_quark,
569 g_object_ref (source_object),
573 /* Ok. So IPv4 is not supported on this platform. If we
574 * succeeded at creating an IPv6 socket then that's OK, but
575 * otherwise we need to tell the user we failed.
579 g_clear_error (error);
585 g_assert (socket6 != NULL || socket4 != NULL);
588 g_ptr_array_add (listener->priv->sockets, socket6);
591 g_ptr_array_add (listener->priv->sockets, socket4);
593 if (G_SOCKET_LISTENER_GET_CLASS (listener)->changed)
594 G_SOCKET_LISTENER_GET_CLASS (listener)->changed (listener);
600 add_sources (GSocketListener *listener,
601 GSocketSourceFunc callback,
602 gpointer callback_data,
603 GCancellable *cancellable,
604 GMainContext *context)
612 for (i = 0; i < listener->priv->sockets->len; i++)
614 socket = listener->priv->sockets->pdata[i];
616 source = g_socket_create_source (socket, G_IO_IN, cancellable);
617 g_source_set_callback (source,
618 (GSourceFunc) callback,
619 callback_data, NULL);
620 g_source_attach (source, context);
622 sources = g_list_prepend (sources, source);
629 free_sources (GList *sources)
632 while (sources != NULL)
634 source = sources->data;
635 sources = g_list_delete_link (sources, sources);
636 g_source_destroy (source);
637 g_source_unref (source);
647 accept_callback (GSocket *socket,
648 GIOCondition condition,
651 struct AcceptData *data = user_data;
653 data->socket = socket;
654 g_main_loop_quit (data->loop);
660 * g_socket_listener_accept_socket:
661 * @listener: a #GSocketListener
662 * @source_object: (out) (transfer none) (optional) (nullable): location where #GObject pointer will be stored, or %NULL.
663 * @cancellable: (nullable): optional #GCancellable object, %NULL to ignore.
664 * @error: #GError for error reporting, or %NULL to ignore.
666 * Blocks waiting for a client to connect to any of the sockets added
667 * to the listener. Returns the #GSocket that was accepted.
669 * If you want to accept the high-level #GSocketConnection, not a #GSocket,
670 * which is often the case, then you should use g_socket_listener_accept()
673 * If @source_object is not %NULL it will be filled out with the source
674 * object specified when the corresponding socket or address was added
677 * If @cancellable is not %NULL, then the operation can be cancelled by
678 * triggering the cancellable object from another thread. If the operation
679 * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
681 * Returns: (transfer full): a #GSocket on success, %NULL on error.
686 g_socket_listener_accept_socket (GSocketListener *listener,
687 GObject **source_object,
688 GCancellable *cancellable,
691 GSocket *accept_socket, *socket;
693 g_return_val_if_fail (G_IS_SOCKET_LISTENER (listener), NULL);
695 if (!check_listener (listener, error))
698 if (listener->priv->sockets->len == 1)
700 accept_socket = listener->priv->sockets->pdata[0];
701 if (!g_socket_condition_wait (accept_socket, G_IO_IN,
708 struct AcceptData data;
711 if (listener->priv->main_context == NULL)
712 listener->priv->main_context = g_main_context_new ();
714 loop = g_main_loop_new (listener->priv->main_context, FALSE);
716 sources = add_sources (listener,
720 listener->priv->main_context);
721 g_main_loop_run (loop);
722 accept_socket = data.socket;
723 free_sources (sources);
724 g_main_loop_unref (loop);
727 if (!(socket = g_socket_accept (accept_socket, cancellable, error)))
731 *source_object = g_object_get_qdata (G_OBJECT (accept_socket), source_quark);
737 * g_socket_listener_accept:
738 * @listener: a #GSocketListener
739 * @source_object: (out) (transfer none) (optional) (nullable): location where #GObject pointer will be stored, or %NULL
740 * @cancellable: (nullable): optional #GCancellable object, %NULL to ignore.
741 * @error: #GError for error reporting, or %NULL to ignore.
743 * Blocks waiting for a client to connect to any of the sockets added
744 * to the listener. Returns a #GSocketConnection for the socket that was
747 * If @source_object is not %NULL it will be filled out with the source
748 * object specified when the corresponding socket or address was added
751 * If @cancellable is not %NULL, then the operation can be cancelled by
752 * triggering the cancellable object from another thread. If the operation
753 * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
755 * Returns: (transfer full): a #GSocketConnection on success, %NULL on error.
760 g_socket_listener_accept (GSocketListener *listener,
761 GObject **source_object,
762 GCancellable *cancellable,
765 GSocketConnection *connection;
768 socket = g_socket_listener_accept_socket (listener,
775 connection = g_socket_connection_factory_create_connection (socket);
776 g_object_unref (socket);
783 GList *sources; /* (element-type GSource) */
784 gboolean returned_yet;
785 } AcceptSocketAsyncData;
788 accept_socket_async_data_free (AcceptSocketAsyncData *data)
790 free_sources (data->sources);
795 accept_ready (GSocket *accept_socket,
796 GIOCondition condition,
799 GTask *task = user_data;
800 GError *error = NULL;
802 GObject *source_object;
803 AcceptSocketAsyncData *data = g_task_get_task_data (task);
805 /* Don’t call g_task_return_*() multiple times if we have multiple incoming
806 * connections in the same #GMainContext iteration. */
807 if (data->returned_yet)
808 return G_SOURCE_REMOVE;
810 socket = g_socket_accept (accept_socket, g_task_get_cancellable (task), &error);
813 source_object = g_object_get_qdata (G_OBJECT (accept_socket), source_quark);
815 g_object_set_qdata_full (G_OBJECT (task),
817 g_object_ref (source_object), g_object_unref);
818 g_task_return_pointer (task, socket, g_object_unref);
822 g_task_return_error (task, error);
825 data->returned_yet = TRUE;
826 g_object_unref (task);
828 return G_SOURCE_REMOVE;
832 * g_socket_listener_accept_socket_async:
833 * @listener: a #GSocketListener
834 * @cancellable: (nullable): a #GCancellable, or %NULL
835 * @callback: (scope async): a #GAsyncReadyCallback
836 * @user_data: (closure): user data for the callback
838 * This is the asynchronous version of g_socket_listener_accept_socket().
840 * When the operation is finished @callback will be
841 * called. You can then call g_socket_listener_accept_socket_finish()
842 * to get the result of the operation.
847 g_socket_listener_accept_socket_async (GSocketListener *listener,
848 GCancellable *cancellable,
849 GAsyncReadyCallback callback,
853 GError *error = NULL;
854 AcceptSocketAsyncData *data = NULL;
856 task = g_task_new (listener, cancellable, callback, user_data);
857 g_task_set_source_tag (task, g_socket_listener_accept_socket_async);
859 if (!check_listener (listener, &error))
861 g_task_return_error (task, error);
862 g_object_unref (task);
866 data = g_new0 (AcceptSocketAsyncData, 1);
867 data->returned_yet = FALSE;
868 data->sources = add_sources (listener,
872 g_main_context_get_thread_default ());
873 g_task_set_task_data (task, g_steal_pointer (&data),
874 (GDestroyNotify) accept_socket_async_data_free);
878 * g_socket_listener_accept_socket_finish:
879 * @listener: a #GSocketListener
880 * @result: a #GAsyncResult.
881 * @source_object: (out) (transfer none) (optional) (nullable): Optional #GObject identifying this source
882 * @error: a #GError location to store the error occurring, or %NULL to
885 * Finishes an async accept operation. See g_socket_listener_accept_socket_async()
887 * Returns: (transfer full): a #GSocket on success, %NULL on error.
892 g_socket_listener_accept_socket_finish (GSocketListener *listener,
893 GAsyncResult *result,
894 GObject **source_object,
897 g_return_val_if_fail (G_IS_SOCKET_LISTENER (listener), NULL);
898 g_return_val_if_fail (g_task_is_valid (result, listener), NULL);
901 *source_object = g_object_get_qdata (G_OBJECT (result), source_quark);
903 return g_task_propagate_pointer (G_TASK (result), error);
907 * g_socket_listener_accept_async:
908 * @listener: a #GSocketListener
909 * @cancellable: (nullable): a #GCancellable, or %NULL
910 * @callback: (scope async): a #GAsyncReadyCallback
911 * @user_data: (closure): user data for the callback
913 * This is the asynchronous version of g_socket_listener_accept().
915 * When the operation is finished @callback will be
916 * called. You can then call g_socket_listener_accept_socket()
917 * to get the result of the operation.
922 g_socket_listener_accept_async (GSocketListener *listener,
923 GCancellable *cancellable,
924 GAsyncReadyCallback callback,
927 g_socket_listener_accept_socket_async (listener,
934 * g_socket_listener_accept_finish:
935 * @listener: a #GSocketListener
936 * @result: a #GAsyncResult.
937 * @source_object: (out) (transfer none) (optional) (nullable): Optional #GObject identifying this source
938 * @error: a #GError location to store the error occurring, or %NULL to
941 * Finishes an async accept operation. See g_socket_listener_accept_async()
943 * Returns: (transfer full): a #GSocketConnection on success, %NULL on error.
948 g_socket_listener_accept_finish (GSocketListener *listener,
949 GAsyncResult *result,
950 GObject **source_object,
954 GSocketConnection *connection;
956 socket = g_socket_listener_accept_socket_finish (listener,
963 connection = g_socket_connection_factory_create_connection (socket);
964 g_object_unref (socket);
969 * g_socket_listener_set_backlog:
970 * @listener: a #GSocketListener
971 * @listen_backlog: an integer
973 * Sets the listen backlog on the sockets in the listener. This must be called
974 * before adding any sockets, addresses or ports to the #GSocketListener (for
975 * example, by calling g_socket_listener_add_inet_port()) to be effective.
977 * See g_socket_set_listen_backlog() for details
982 g_socket_listener_set_backlog (GSocketListener *listener,
988 if (listener->priv->closed)
991 listener->priv->listen_backlog = listen_backlog;
993 for (i = 0; i < listener->priv->sockets->len; i++)
995 socket = listener->priv->sockets->pdata[i];
996 g_socket_set_listen_backlog (socket, listen_backlog);
1001 * g_socket_listener_close:
1002 * @listener: a #GSocketListener
1004 * Closes all the sockets in the listener.
1009 g_socket_listener_close (GSocketListener *listener)
1014 g_return_if_fail (G_IS_SOCKET_LISTENER (listener));
1016 if (listener->priv->closed)
1019 for (i = 0; i < listener->priv->sockets->len; i++)
1021 socket = listener->priv->sockets->pdata[i];
1022 g_socket_close (socket, NULL);
1024 listener->priv->closed = TRUE;
1028 * g_socket_listener_add_any_inet_port:
1029 * @listener: a #GSocketListener
1030 * @source_object: (nullable): Optional #GObject identifying this source
1031 * @error: a #GError location to store the error occurring, or %NULL to
1034 * Listens for TCP connections on any available port number for both
1035 * IPv6 and IPv4 (if each is available).
1037 * This is useful if you need to have a socket for incoming connections
1038 * but don't care about the specific port number.
1040 * @source_object will be passed out in the various calls
1041 * to accept to identify this particular source, which is
1042 * useful if you're listening on multiple addresses and do
1043 * different things depending on what address is connected to.
1045 * Returns: the port number, or 0 in case of failure.
1050 g_socket_listener_add_any_inet_port (GSocketListener *listener,
1051 GObject *source_object,
1054 GSList *sockets_to_close = NULL;
1055 guint16 candidate_port = 0;
1056 GSocket *socket6 = NULL;
1057 GSocket *socket4 = NULL;
1061 * multi-step process:
1062 * - first, create an IPv6 socket.
1063 * - if that fails, create an IPv4 socket and bind it to port 0 and
1064 * that's it. no retries if that fails (why would it?).
1065 * - if our IPv6 socket also speaks IPv4 then we are done.
1066 * - if not, then we need to create a IPv4 socket with the same port
1067 * number. this might fail, of course. so we try this a bunch of
1068 * times -- leaving the old IPv6 sockets open so that we get a
1069 * different port number to try each time.
1070 * - if all that fails then just give up.
1075 GInetAddress *inet_address;
1076 GSocketAddress *address;
1079 g_assert (socket6 == NULL);
1080 socket6 = g_socket_new (G_SOCKET_FAMILY_IPV6,
1081 G_SOCKET_TYPE_STREAM,
1082 G_SOCKET_PROTOCOL_DEFAULT,
1085 if (socket6 != NULL)
1087 inet_address = g_inet_address_new_any (G_SOCKET_FAMILY_IPV6);
1088 address = g_inet_socket_address_new (inet_address, 0);
1089 g_object_unref (inet_address);
1091 g_signal_emit (listener, signals[EVENT], 0,
1092 G_SOCKET_LISTENER_BINDING, socket6);
1094 result = g_socket_bind (socket6, address, TRUE, error);
1095 g_object_unref (address);
1098 !(address = g_socket_get_local_address (socket6, error)))
1100 g_object_unref (socket6);
1105 g_signal_emit (listener, signals[EVENT], 0,
1106 G_SOCKET_LISTENER_BOUND, socket6);
1108 g_assert (G_IS_INET_SOCKET_ADDRESS (address));
1110 g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (address));
1111 g_assert (candidate_port != 0);
1112 g_object_unref (address);
1114 if (g_socket_speaks_ipv4 (socket6))
1118 g_assert (socket4 == NULL);
1119 socket4 = g_socket_new (G_SOCKET_FAMILY_IPV4,
1120 G_SOCKET_TYPE_STREAM,
1121 G_SOCKET_PROTOCOL_DEFAULT,
1122 socket6 ? NULL : error);
1124 if (socket4 == NULL)
1125 /* IPv4 not supported.
1126 * if IPv6 is supported then candidate_port will be non-zero
1127 * (and the error parameter above will have been NULL)
1128 * if IPv6 is unsupported then candidate_port will be zero
1129 * (and error will have been set by the above call)
1133 inet_address = g_inet_address_new_any (G_SOCKET_FAMILY_IPV4);
1134 address = g_inet_socket_address_new (inet_address, candidate_port);
1135 g_object_unref (inet_address);
1137 g_signal_emit (listener, signals[EVENT], 0,
1138 G_SOCKET_LISTENER_BINDING, socket4);
1140 /* a note on the 'error' clause below:
1142 * if candidate_port is 0 then we report the error right away
1143 * since it is strange that this binding would fail at all.
1144 * otherwise, we ignore the error message (ie: NULL).
1146 * the exception to this rule is the last time through the loop
1147 * (ie: attempts == 0) in which case we want to set the error
1148 * because failure here means that the entire call will fail and
1149 * we need something to show to the user.
1151 * an english summary of the situation: "if we gave a candidate
1152 * port number AND we have more attempts to try, then ignore the
1155 result = g_socket_bind (socket4, address, TRUE,
1156 (candidate_port && attempts) ? NULL : error);
1157 g_object_unref (address);
1161 g_assert (socket6 != NULL);
1164 /* got our candidate port successfully */
1166 g_signal_emit (listener, signals[EVENT], 0,
1167 G_SOCKET_LISTENER_BOUND, socket4);
1171 /* we failed to bind to the specified port. try again. */
1173 g_object_unref (socket4);
1176 /* keep this open so we get a different port number */
1177 sockets_to_close = g_slist_prepend (sockets_to_close,
1184 /* we didn't tell it a port. this means two things.
1185 * - if we failed, then something really bad happened.
1186 * - if we succeeded, then we need to find out the port number.
1189 g_assert (socket6 == NULL);
1192 !(address = g_socket_get_local_address (socket4, error)))
1194 g_object_unref (socket4);
1199 g_signal_emit (listener, signals[EVENT], 0,
1200 G_SOCKET_LISTENER_BOUND, socket4);
1202 g_assert (G_IS_INET_SOCKET_ADDRESS (address));
1204 g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (address));
1205 g_assert (candidate_port != 0);
1206 g_object_unref (address);
1211 /* should only be non-zero if we have a socket */
1212 g_assert ((candidate_port != 0) == (socket4 || socket6));
1214 while (sockets_to_close)
1216 g_object_unref (sockets_to_close->data);
1217 sockets_to_close = g_slist_delete_link (sockets_to_close,
1221 /* now we actually listen() the sockets and add them to the listener */
1222 if (socket6 != NULL)
1224 g_socket_set_listen_backlog (socket6, listener->priv->listen_backlog);
1226 g_signal_emit (listener, signals[EVENT], 0,
1227 G_SOCKET_LISTENER_LISTENING, socket6);
1229 if (!g_socket_listen (socket6, error))
1231 g_object_unref (socket6);
1233 g_object_unref (socket4);
1238 g_signal_emit (listener, signals[EVENT], 0,
1239 G_SOCKET_LISTENER_LISTENED, socket6);
1242 g_object_set_qdata_full (G_OBJECT (socket6), source_quark,
1243 g_object_ref (source_object),
1246 g_ptr_array_add (listener->priv->sockets, socket6);
1249 if (socket4 != NULL)
1251 g_socket_set_listen_backlog (socket4, listener->priv->listen_backlog);
1253 g_signal_emit (listener, signals[EVENT], 0,
1254 G_SOCKET_LISTENER_LISTENING, socket4);
1256 if (!g_socket_listen (socket4, error))
1258 g_object_unref (socket4);
1260 g_object_unref (socket6);
1265 g_signal_emit (listener, signals[EVENT], 0,
1266 G_SOCKET_LISTENER_LISTENED, socket4);
1269 g_object_set_qdata_full (G_OBJECT (socket4), source_quark,
1270 g_object_ref (source_object),
1273 g_ptr_array_add (listener->priv->sockets, socket4);
1276 if ((socket4 != NULL || socket6 != NULL) &&
1277 G_SOCKET_LISTENER_GET_CLASS (listener)->changed)
1278 G_SOCKET_LISTENER_GET_CLASS (listener)->changed (listener);
1280 return candidate_port;