gio/auto/
socket.rs

1// This file was generated by gir (https://github.com/gtk-rs/gir)
2// from gir-files (https://github.com/gtk-rs/gir-files)
3// DO NOT EDIT
4
5use crate::{
6    ffi, Cancellable, Credentials, DatagramBased, InetAddress, Initable, SocketAddress,
7    SocketConnection, SocketFamily, SocketProtocol, SocketType,
8};
9use glib::{
10    prelude::*,
11    signal::{connect_raw, SignalHandlerId},
12    translate::*,
13};
14use std::boxed::Box as Box_;
15
16glib::wrapper! {
17    /// A `GSocket` is a low-level networking primitive. It is a more or less
18    /// direct mapping of the BSD socket API in a portable GObject based API.
19    /// It supports both the UNIX socket implementations and winsock2 on Windows.
20    ///
21    /// `GSocket` is the platform independent base upon which the higher level
22    /// network primitives are based. Applications are not typically meant to
23    /// use it directly, but rather through classes like [`SocketClient`][crate::SocketClient],
24    /// [`SocketService`][crate::SocketService] and [`SocketConnection`][crate::SocketConnection]. However there may
25    /// be cases where direct use of `GSocket` is useful.
26    ///
27    /// `GSocket` implements the [`Initable`][crate::Initable] interface, so if it is manually
28    /// constructed by e.g. [`glib::Object::new()`][crate::glib::Object::new()] you must call
29    /// [`InitableExt::init()`][crate::prelude::InitableExt::init()] and check the results before using the object.
30    /// This is done automatically in [`new()`][Self::new()] and
31    /// [`from_fd()`][Self::from_fd()], so these functions can return `NULL`.
32    ///
33    /// Sockets operate in two general modes, blocking or non-blocking. When
34    /// in blocking mode all operations (which don’t take an explicit blocking
35    /// parameter) block until the requested operation
36    /// is finished or there is an error. In non-blocking mode all calls that
37    /// would block return immediately with a `G_IO_ERROR_WOULD_BLOCK` error.
38    /// To know when a call would successfully run you can call
39    /// [`SocketExt::condition_check()`][crate::prelude::SocketExt::condition_check()], or [`SocketExt::condition_wait()`][crate::prelude::SocketExt::condition_wait()].
40    /// You can also use `Gio::Socket::create_source()` and attach it to a
41    /// [type@GLib.MainContext] to get callbacks when I/O is possible.
42    /// Note that all sockets are always set to non blocking mode in the system, and
43    /// blocking mode is emulated in `GSocket`.
44    ///
45    /// When working in non-blocking mode applications should always be able to
46    /// handle getting a `G_IO_ERROR_WOULD_BLOCK` error even when some other
47    /// function said that I/O was possible. This can easily happen in case
48    /// of a race condition in the application, but it can also happen for other
49    /// reasons. For instance, on Windows a socket is always seen as writable
50    /// until a write returns `G_IO_ERROR_WOULD_BLOCK`.
51    ///
52    /// `GSocket`s can be either connection oriented or datagram based.
53    /// For connection oriented types you must first establish a connection by
54    /// either connecting to an address or accepting a connection from another
55    /// address. For connectionless socket types the target/source address is
56    /// specified or received in each I/O operation.
57    ///
58    /// All socket file descriptors are set to be close-on-exec.
59    ///
60    /// Note that creating a `GSocket` causes the signal `SIGPIPE` to be
61    /// ignored for the remainder of the program. If you are writing a
62    /// command-line utility that uses `GSocket`, you may need to take into
63    /// account the fact that your program will not automatically be killed
64    /// if it tries to write to `stdout` after it has been closed.
65    ///
66    /// Like most other APIs in GLib, `GSocket` is not inherently thread safe. To use
67    /// a `GSocket` concurrently from multiple threads, you must implement your own
68    /// locking.
69    ///
70    /// ## Nagle’s algorithm
71    ///
72    /// Since GLib 2.80, `GSocket` will automatically set the `TCP_NODELAY` option on
73    /// all `G_SOCKET_TYPE_STREAM` sockets. This disables
74    /// [Nagle’s algorithm](https://en.wikipedia.org/wiki/Nagle`27s_algorithm`) as it
75    /// typically does more harm than good on modern networks.
76    ///
77    /// If your application needs Nagle’s algorithm enabled, call
78    /// [`SocketExt::set_option()`][crate::prelude::SocketExt::set_option()] after constructing a `GSocket` to enable it:
79    /// **⚠️ The following code is in c ⚠️**
80    ///
81    /// ```c
82    /// socket = g_socket_new (…, G_SOCKET_TYPE_STREAM, …);
83    /// if (socket != NULL)
84    ///   {
85    ///     g_socket_set_option (socket, IPPROTO_TCP, TCP_NODELAY, FALSE, &local_error);
86    ///     // handle error if needed
87    ///   }
88    /// ```
89    ///
90    /// ## Properties
91    ///
92    ///
93    /// #### `blocking`
94    ///  Whether I/O on this socket is blocking.
95    ///
96    /// Readable | Writeable
97    ///
98    ///
99    /// #### `broadcast`
100    ///  Whether the socket should allow sending to broadcast addresses.
101    ///
102    /// Readable | Writeable
103    ///
104    ///
105    /// #### `family`
106    ///  The socket’s address family.
107    ///
108    /// Readable | Writeable | Construct Only
109    ///
110    ///
111    /// #### `fd`
112    ///  The socket’s file descriptor.
113    ///
114    /// Readable | Writeable | Construct Only
115    ///
116    ///
117    /// #### `keepalive`
118    ///  Whether to keep the connection alive by sending periodic pings.
119    ///
120    /// Readable | Writeable
121    ///
122    ///
123    /// #### `listen-backlog`
124    ///  The number of outstanding connections in the listen queue.
125    ///
126    /// Readable | Writeable
127    ///
128    ///
129    /// #### `local-address`
130    ///  The local address the socket is bound to.
131    ///
132    /// Readable
133    ///
134    ///
135    /// #### `multicast-loopback`
136    ///  Whether outgoing multicast packets loop back to the local host.
137    ///
138    /// Readable | Writeable
139    ///
140    ///
141    /// #### `multicast-ttl`
142    ///  Time-to-live out outgoing multicast packets
143    ///
144    /// Readable | Writeable
145    ///
146    ///
147    /// #### `protocol`
148    ///  The ID of the protocol to use, or `-1` for unknown.
149    ///
150    /// Readable | Writeable | Construct Only
151    ///
152    ///
153    /// #### `remote-address`
154    ///  The remote address the socket is connected to.
155    ///
156    /// Readable
157    ///
158    ///
159    /// #### `timeout`
160    ///  The timeout in seconds on socket I/O
161    ///
162    /// Readable | Writeable
163    ///
164    ///
165    /// #### `ttl`
166    ///  Time-to-live for outgoing unicast packets
167    ///
168    /// Readable | Writeable
169    ///
170    ///
171    /// #### `type`
172    ///  The socket’s type.
173    ///
174    /// Readable | Writeable | Construct Only
175    ///
176    /// # Implements
177    ///
178    /// [`SocketExt`][trait@crate::prelude::SocketExt], [`trait@glib::ObjectExt`], [`DatagramBasedExt`][trait@crate::prelude::DatagramBasedExt], [`InitableExt`][trait@crate::prelude::InitableExt], [`SocketExtManual`][trait@crate::prelude::SocketExtManual], [`DatagramBasedExtManual`][trait@crate::prelude::DatagramBasedExtManual]
179    #[doc(alias = "GSocket")]
180    pub struct Socket(Object<ffi::GSocket, ffi::GSocketClass>) @implements DatagramBased, Initable;
181
182    match fn {
183        type_ => || ffi::g_socket_get_type(),
184    }
185}
186
187impl Socket {
188    pub const NONE: Option<&'static Socket> = None;
189
190    /// Creates a new #GSocket with the defined family, type and protocol.
191    /// If @protocol is 0 ([`SocketProtocol::Default`][crate::SocketProtocol::Default]) the default protocol type
192    /// for the family and type is used.
193    ///
194    /// The @protocol is a family and type specific int that specifies what
195    /// kind of protocol to use. #GSocketProtocol lists several common ones.
196    /// Many families only support one protocol, and use 0 for this, others
197    /// support several and using 0 means to use the default protocol for
198    /// the family and type.
199    ///
200    /// The protocol id is passed directly to the operating
201    /// system, so you can use protocols not listed in #GSocketProtocol if you
202    /// know the protocol number used for it.
203    /// ## `family`
204    /// the socket family to use, e.g. [`SocketFamily::Ipv4`][crate::SocketFamily::Ipv4].
205    /// ## `type_`
206    /// the socket type to use.
207    /// ## `protocol`
208    /// the id of the protocol to use, or 0 for default.
209    ///
210    /// # Returns
211    ///
212    /// a #GSocket or [`None`] on error.
213    ///     Free the returned object with g_object_unref().
214    #[doc(alias = "g_socket_new")]
215    pub fn new(
216        family: SocketFamily,
217        type_: SocketType,
218        protocol: SocketProtocol,
219    ) -> Result<Socket, glib::Error> {
220        unsafe {
221            let mut error = std::ptr::null_mut();
222            let ret = ffi::g_socket_new(
223                family.into_glib(),
224                type_.into_glib(),
225                protocol.into_glib(),
226                &mut error,
227            );
228            if error.is_null() {
229                Ok(from_glib_full(ret))
230            } else {
231                Err(from_glib_full(error))
232            }
233        }
234    }
235}
236
237/// Trait containing all [`struct@Socket`] methods.
238///
239/// # Implementors
240///
241/// [`Socket`][struct@crate::Socket]
242pub trait SocketExt: IsA<Socket> + 'static {
243    /// Accept incoming connections on a connection-based socket. This removes
244    /// the first outstanding connection request from the listening socket and
245    /// creates a #GSocket object for it.
246    ///
247    /// The @self must be bound to a local address with g_socket_bind() and
248    /// must be listening for incoming connections (g_socket_listen()).
249    ///
250    /// If there are no outstanding connections then the operation will block
251    /// or return [`IOErrorEnum::WouldBlock`][crate::IOErrorEnum::WouldBlock] if non-blocking I/O is enabled.
252    /// To be notified of an incoming connection, wait for the [`glib::IOCondition::IN`][crate::glib::IOCondition::IN] condition.
253    /// ## `cancellable`
254    /// a `GCancellable` or [`None`]
255    ///
256    /// # Returns
257    ///
258    /// a new #GSocket, or [`None`] on error.
259    ///     Free the returned object with g_object_unref().
260    #[doc(alias = "g_socket_accept")]
261    fn accept(&self, cancellable: Option<&impl IsA<Cancellable>>) -> Result<Socket, glib::Error> {
262        unsafe {
263            let mut error = std::ptr::null_mut();
264            let ret = ffi::g_socket_accept(
265                self.as_ref().to_glib_none().0,
266                cancellable.map(|p| p.as_ref()).to_glib_none().0,
267                &mut error,
268            );
269            if error.is_null() {
270                Ok(from_glib_full(ret))
271            } else {
272                Err(from_glib_full(error))
273            }
274        }
275    }
276
277    /// When a socket is created it is attached to an address family, but it
278    /// doesn't have an address in this family. g_socket_bind() assigns the
279    /// address (sometimes called name) of the socket.
280    ///
281    /// It is generally required to bind to a local address before you can
282    /// receive connections. (See g_socket_listen() and g_socket_accept() ).
283    /// In certain situations, you may also want to bind a socket that will be
284    /// used to initiate connections, though this is not normally required.
285    ///
286    /// If @self is a TCP socket, then @allow_reuse controls the setting
287    /// of the `SO_REUSEADDR` socket option; normally it should be [`true`] for
288    /// server sockets (sockets that you will eventually call
289    /// g_socket_accept() on), and [`false`] for client sockets. (Failing to
290    /// set this flag on a server socket may cause g_socket_bind() to return
291    /// [`IOErrorEnum::AddressInUse`][crate::IOErrorEnum::AddressInUse] if the server program is stopped and then
292    /// immediately restarted.)
293    ///
294    /// If @self is a UDP socket, then @allow_reuse determines whether or
295    /// not other UDP sockets can be bound to the same address at the same
296    /// time. In particular, you can have several UDP sockets bound to the
297    /// same address, and they will all receive all of the multicast and
298    /// broadcast packets sent to that address. (The behavior of unicast
299    /// UDP packets to an address with multiple listeners is not defined.)
300    /// ## `address`
301    /// a #GSocketAddress specifying the local address.
302    /// ## `allow_reuse`
303    /// whether to allow reusing this address
304    ///
305    /// # Returns
306    ///
307    /// [`true`] on success, [`false`] on error.
308    #[doc(alias = "g_socket_bind")]
309    fn bind(
310        &self,
311        address: &impl IsA<SocketAddress>,
312        allow_reuse: bool,
313    ) -> Result<(), glib::Error> {
314        unsafe {
315            let mut error = std::ptr::null_mut();
316            let is_ok = ffi::g_socket_bind(
317                self.as_ref().to_glib_none().0,
318                address.as_ref().to_glib_none().0,
319                allow_reuse.into_glib(),
320                &mut error,
321            );
322            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
323            if error.is_null() {
324                Ok(())
325            } else {
326                Err(from_glib_full(error))
327            }
328        }
329    }
330
331    /// Checks and resets the pending connect error for the socket.
332    /// This is used to check for errors when g_socket_connect() is
333    /// used in non-blocking mode.
334    ///
335    /// # Returns
336    ///
337    /// [`true`] if no error, [`false`] otherwise, setting @error to the error
338    #[doc(alias = "g_socket_check_connect_result")]
339    fn check_connect_result(&self) -> Result<(), glib::Error> {
340        unsafe {
341            let mut error = std::ptr::null_mut();
342            let is_ok =
343                ffi::g_socket_check_connect_result(self.as_ref().to_glib_none().0, &mut error);
344            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
345            if error.is_null() {
346                Ok(())
347            } else {
348                Err(from_glib_full(error))
349            }
350        }
351    }
352
353    /// Closes the socket, shutting down any active connection.
354    ///
355    /// Closing a socket does not wait for all outstanding I/O operations
356    /// to finish, so the caller should not rely on them to be guaranteed
357    /// to complete even if the close returns with no error.
358    ///
359    /// Once the socket is closed, all other operations will return
360    /// [`IOErrorEnum::Closed`][crate::IOErrorEnum::Closed]. Closing a socket multiple times will not
361    /// return an error.
362    ///
363    /// Sockets will be automatically closed when the last reference
364    /// is dropped, but you might want to call this function to make sure
365    /// resources are released as early as possible.
366    ///
367    /// Beware that due to the way that TCP works, it is possible for
368    /// recently-sent data to be lost if either you close a socket while the
369    /// [`glib::IOCondition::IN`][crate::glib::IOCondition::IN] condition is set, or else if the remote connection tries to
370    /// send something to you after you close the socket but before it has
371    /// finished reading all of the data you sent. There is no easy generic
372    /// way to avoid this problem; the easiest fix is to design the network
373    /// protocol such that the client will never send data "out of turn".
374    /// Another solution is for the server to half-close the connection by
375    /// calling g_socket_shutdown() with only the @shutdown_write flag set,
376    /// and then wait for the client to notice this and close its side of the
377    /// connection, after which the server can safely call g_socket_close().
378    /// (This is what #GTcpConnection does if you call
379    /// g_tcp_connection_set_graceful_disconnect(). But of course, this
380    /// only works if the client will close its connection after the server
381    /// does.)
382    ///
383    /// # Returns
384    ///
385    /// [`true`] on success, [`false`] on error
386    #[doc(alias = "g_socket_close")]
387    fn close(&self) -> Result<(), glib::Error> {
388        unsafe {
389            let mut error = std::ptr::null_mut();
390            let is_ok = ffi::g_socket_close(self.as_ref().to_glib_none().0, &mut error);
391            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
392            if error.is_null() {
393                Ok(())
394            } else {
395                Err(from_glib_full(error))
396            }
397        }
398    }
399
400    /// Checks on the readiness of @self to perform operations.
401    /// The operations specified in @condition are checked for and masked
402    /// against the currently-satisfied conditions on @self. The result
403    /// is returned.
404    ///
405    /// Note that on Windows, it is possible for an operation to return
406    /// [`IOErrorEnum::WouldBlock`][crate::IOErrorEnum::WouldBlock] even immediately after
407    /// g_socket_condition_check() has claimed that the socket is ready for
408    /// writing. Rather than calling g_socket_condition_check() and then
409    /// writing to the socket if it succeeds, it is generally better to
410    /// simply try writing to the socket right away, and try again later if
411    /// the initial attempt returns [`IOErrorEnum::WouldBlock`][crate::IOErrorEnum::WouldBlock].
412    ///
413    /// It is meaningless to specify [`glib::IOCondition::ERR`][crate::glib::IOCondition::ERR] or [`glib::IOCondition::HUP`][crate::glib::IOCondition::HUP] in condition;
414    /// these conditions will always be set in the output if they are true.
415    ///
416    /// This call never blocks.
417    /// ## `condition`
418    /// a #GIOCondition mask to check
419    ///
420    /// # Returns
421    ///
422    /// the @GIOCondition mask of the current state
423    #[doc(alias = "g_socket_condition_check")]
424    fn condition_check(&self, condition: glib::IOCondition) -> glib::IOCondition {
425        unsafe {
426            from_glib(ffi::g_socket_condition_check(
427                self.as_ref().to_glib_none().0,
428                condition.into_glib(),
429            ))
430        }
431    }
432
433    /// Waits for up to @timeout_us microseconds for @condition to become true
434    /// on @self. If the condition is met, [`true`] is returned.
435    ///
436    /// If @cancellable is cancelled before the condition is met, or if
437    /// @timeout_us (or the socket's #GSocket:timeout) is reached before the
438    /// condition is met, then [`false`] is returned and @error, if non-[`None`],
439    /// is set to the appropriate value ([`IOErrorEnum::Cancelled`][crate::IOErrorEnum::Cancelled] or
440    /// [`IOErrorEnum::TimedOut`][crate::IOErrorEnum::TimedOut]).
441    ///
442    /// If you don't want a timeout, use g_socket_condition_wait().
443    /// (Alternatively, you can pass -1 for @timeout_us.)
444    ///
445    /// Note that although @timeout_us is in microseconds for consistency with
446    /// other GLib APIs, this function actually only has millisecond
447    /// resolution, and the behavior is undefined if @timeout_us is not an
448    /// exact number of milliseconds.
449    /// ## `condition`
450    /// a #GIOCondition mask to wait for
451    /// ## `timeout_us`
452    /// the maximum time (in microseconds) to wait, or -1
453    /// ## `cancellable`
454    /// a #GCancellable, or [`None`]
455    ///
456    /// # Returns
457    ///
458    /// [`true`] if the condition was met, [`false`] otherwise
459    #[doc(alias = "g_socket_condition_timed_wait")]
460    fn condition_timed_wait(
461        &self,
462        condition: glib::IOCondition,
463        timeout_us: i64,
464        cancellable: Option<&impl IsA<Cancellable>>,
465    ) -> Result<(), glib::Error> {
466        unsafe {
467            let mut error = std::ptr::null_mut();
468            let is_ok = ffi::g_socket_condition_timed_wait(
469                self.as_ref().to_glib_none().0,
470                condition.into_glib(),
471                timeout_us,
472                cancellable.map(|p| p.as_ref()).to_glib_none().0,
473                &mut error,
474            );
475            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
476            if error.is_null() {
477                Ok(())
478            } else {
479                Err(from_glib_full(error))
480            }
481        }
482    }
483
484    /// Waits for @condition to become true on @self. When the condition
485    /// is met, [`true`] is returned.
486    ///
487    /// If @cancellable is cancelled before the condition is met, or if the
488    /// socket has a timeout set and it is reached before the condition is
489    /// met, then [`false`] is returned and @error, if non-[`None`], is set to
490    /// the appropriate value ([`IOErrorEnum::Cancelled`][crate::IOErrorEnum::Cancelled] or
491    /// [`IOErrorEnum::TimedOut`][crate::IOErrorEnum::TimedOut]).
492    ///
493    /// See also g_socket_condition_timed_wait().
494    /// ## `condition`
495    /// a #GIOCondition mask to wait for
496    /// ## `cancellable`
497    /// a #GCancellable, or [`None`]
498    ///
499    /// # Returns
500    ///
501    /// [`true`] if the condition was met, [`false`] otherwise
502    #[doc(alias = "g_socket_condition_wait")]
503    fn condition_wait(
504        &self,
505        condition: glib::IOCondition,
506        cancellable: Option<&impl IsA<Cancellable>>,
507    ) -> Result<(), glib::Error> {
508        unsafe {
509            let mut error = std::ptr::null_mut();
510            let is_ok = ffi::g_socket_condition_wait(
511                self.as_ref().to_glib_none().0,
512                condition.into_glib(),
513                cancellable.map(|p| p.as_ref()).to_glib_none().0,
514                &mut error,
515            );
516            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
517            if error.is_null() {
518                Ok(())
519            } else {
520                Err(from_glib_full(error))
521            }
522        }
523    }
524
525    /// Connect the socket to the specified remote address.
526    ///
527    /// For connection oriented socket this generally means we attempt to make
528    /// a connection to the @address. For a connection-less socket it sets
529    /// the default address for g_socket_send() and discards all incoming datagrams
530    /// from other sources.
531    ///
532    /// Generally connection oriented sockets can only connect once, but
533    /// connection-less sockets can connect multiple times to change the
534    /// default address.
535    ///
536    /// If the connect call needs to do network I/O it will block, unless
537    /// non-blocking I/O is enabled. Then [`IOErrorEnum::Pending`][crate::IOErrorEnum::Pending] is returned
538    /// and the user can be notified of the connection finishing by waiting
539    /// for the G_IO_OUT condition. The result of the connection must then be
540    /// checked with g_socket_check_connect_result().
541    /// ## `address`
542    /// a #GSocketAddress specifying the remote address.
543    /// ## `cancellable`
544    /// a `GCancellable` or [`None`]
545    ///
546    /// # Returns
547    ///
548    /// [`true`] if connected, [`false`] on error.
549    #[doc(alias = "g_socket_connect")]
550    fn connect(
551        &self,
552        address: &impl IsA<SocketAddress>,
553        cancellable: Option<&impl IsA<Cancellable>>,
554    ) -> Result<(), glib::Error> {
555        unsafe {
556            let mut error = std::ptr::null_mut();
557            let is_ok = ffi::g_socket_connect(
558                self.as_ref().to_glib_none().0,
559                address.as_ref().to_glib_none().0,
560                cancellable.map(|p| p.as_ref()).to_glib_none().0,
561                &mut error,
562            );
563            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
564            if error.is_null() {
565                Ok(())
566            } else {
567                Err(from_glib_full(error))
568            }
569        }
570    }
571
572    /// Creates a #GSocketConnection subclass of the right type for
573    /// @self.
574    ///
575    /// # Returns
576    ///
577    /// a #GSocketConnection
578    #[doc(alias = "g_socket_connection_factory_create_connection")]
579    fn connection_factory_create_connection(&self) -> SocketConnection {
580        unsafe {
581            from_glib_full(ffi::g_socket_connection_factory_create_connection(
582                self.as_ref().to_glib_none().0,
583            ))
584        }
585    }
586
587    /// Get the amount of data pending in the OS input buffer, without blocking.
588    ///
589    /// If @self is a UDP or SCTP socket, this will return the size of
590    /// just the next packet, even if additional packets are buffered after
591    /// that one.
592    ///
593    /// Note that on Windows, this function is rather inefficient in the
594    /// UDP case, and so if you know any plausible upper bound on the size
595    /// of the incoming packet, it is better to just do a
596    /// g_socket_receive() with a buffer of that size, rather than calling
597    /// g_socket_get_available_bytes() first and then doing a receive of
598    /// exactly the right size.
599    ///
600    /// # Returns
601    ///
602    /// the number of bytes that can be read from the socket
603    /// without blocking or truncating, or -1 on error.
604    #[doc(alias = "g_socket_get_available_bytes")]
605    #[doc(alias = "get_available_bytes")]
606    fn available_bytes(&self) -> isize {
607        unsafe { ffi::g_socket_get_available_bytes(self.as_ref().to_glib_none().0) }
608    }
609
610    /// Gets the blocking mode of the socket. For details on blocking I/O,
611    /// see g_socket_set_blocking().
612    ///
613    /// # Returns
614    ///
615    /// [`true`] if blocking I/O is used, [`false`] otherwise.
616    #[doc(alias = "g_socket_get_blocking")]
617    #[doc(alias = "get_blocking")]
618    #[doc(alias = "blocking")]
619    fn is_blocking(&self) -> bool {
620        unsafe { from_glib(ffi::g_socket_get_blocking(self.as_ref().to_glib_none().0)) }
621    }
622
623    /// Gets the broadcast setting on @self; if [`true`],
624    /// it is possible to send packets to broadcast
625    /// addresses.
626    ///
627    /// # Returns
628    ///
629    /// the broadcast setting on @self
630    #[doc(alias = "g_socket_get_broadcast")]
631    #[doc(alias = "get_broadcast")]
632    #[doc(alias = "broadcast")]
633    fn is_broadcast(&self) -> bool {
634        unsafe { from_glib(ffi::g_socket_get_broadcast(self.as_ref().to_glib_none().0)) }
635    }
636
637    /// Returns the credentials of the foreign process connected to this
638    /// socket, if any (e.g. it is only supported for [`SocketFamily::Unix`][crate::SocketFamily::Unix]
639    /// sockets).
640    ///
641    /// If this operation isn't supported on the OS, the method fails with
642    /// the [`IOErrorEnum::NotSupported`][crate::IOErrorEnum::NotSupported] error. On Linux this is implemented
643    /// by reading the `SO_PEERCRED` option on the underlying socket.
644    ///
645    /// This method can be expected to be available on the following platforms:
646    ///
647    /// - Linux since GLib 2.26
648    /// - OpenBSD since GLib 2.30
649    /// - Solaris, Illumos and OpenSolaris since GLib 2.40
650    /// - NetBSD since GLib 2.42
651    /// - macOS, tvOS, iOS since GLib 2.66
652    ///
653    /// Other ways to obtain credentials from a foreign peer includes the
654    /// #GUnixCredentialsMessage type and
655    /// g_unix_connection_send_credentials() /
656    /// g_unix_connection_receive_credentials() functions.
657    ///
658    /// # Returns
659    ///
660    /// [`None`] if @error is set, otherwise a #GCredentials object
661    /// that must be freed with g_object_unref().
662    #[doc(alias = "g_socket_get_credentials")]
663    #[doc(alias = "get_credentials")]
664    fn credentials(&self) -> Result<Credentials, glib::Error> {
665        unsafe {
666            let mut error = std::ptr::null_mut();
667            let ret = ffi::g_socket_get_credentials(self.as_ref().to_glib_none().0, &mut error);
668            if error.is_null() {
669                Ok(from_glib_full(ret))
670            } else {
671                Err(from_glib_full(error))
672            }
673        }
674    }
675
676    /// Gets the socket family of the socket.
677    ///
678    /// # Returns
679    ///
680    /// a #GSocketFamily
681    #[doc(alias = "g_socket_get_family")]
682    #[doc(alias = "get_family")]
683    fn family(&self) -> SocketFamily {
684        unsafe { from_glib(ffi::g_socket_get_family(self.as_ref().to_glib_none().0)) }
685    }
686
687    /// Gets the keepalive mode of the socket. For details on this,
688    /// see g_socket_set_keepalive().
689    ///
690    /// # Returns
691    ///
692    /// [`true`] if keepalive is active, [`false`] otherwise.
693    #[doc(alias = "g_socket_get_keepalive")]
694    #[doc(alias = "get_keepalive")]
695    #[doc(alias = "keepalive")]
696    fn is_keepalive(&self) -> bool {
697        unsafe { from_glib(ffi::g_socket_get_keepalive(self.as_ref().to_glib_none().0)) }
698    }
699
700    /// Gets the listen backlog setting of the socket. For details on this,
701    /// see g_socket_set_listen_backlog().
702    ///
703    /// # Returns
704    ///
705    /// the maximum number of pending connections.
706    #[doc(alias = "g_socket_get_listen_backlog")]
707    #[doc(alias = "get_listen_backlog")]
708    #[doc(alias = "listen-backlog")]
709    fn listen_backlog(&self) -> i32 {
710        unsafe { ffi::g_socket_get_listen_backlog(self.as_ref().to_glib_none().0) }
711    }
712
713    /// Try to get the local address of a bound socket. This is only
714    /// useful if the socket has been bound to a local address,
715    /// either explicitly or implicitly when connecting.
716    ///
717    /// # Returns
718    ///
719    /// a #GSocketAddress or [`None`] on error.
720    ///     Free the returned object with g_object_unref().
721    #[doc(alias = "g_socket_get_local_address")]
722    #[doc(alias = "get_local_address")]
723    #[doc(alias = "local-address")]
724    fn local_address(&self) -> Result<SocketAddress, glib::Error> {
725        unsafe {
726            let mut error = std::ptr::null_mut();
727            let ret = ffi::g_socket_get_local_address(self.as_ref().to_glib_none().0, &mut error);
728            if error.is_null() {
729                Ok(from_glib_full(ret))
730            } else {
731                Err(from_glib_full(error))
732            }
733        }
734    }
735
736    /// Gets the multicast loopback setting on @self; if [`true`] (the
737    /// default), outgoing multicast packets will be looped back to
738    /// multicast listeners on the same host.
739    ///
740    /// # Returns
741    ///
742    /// the multicast loopback setting on @self
743    #[doc(alias = "g_socket_get_multicast_loopback")]
744    #[doc(alias = "get_multicast_loopback")]
745    #[doc(alias = "multicast-loopback")]
746    fn is_multicast_loopback(&self) -> bool {
747        unsafe {
748            from_glib(ffi::g_socket_get_multicast_loopback(
749                self.as_ref().to_glib_none().0,
750            ))
751        }
752    }
753
754    /// Gets the multicast time-to-live setting on @self; see
755    /// g_socket_set_multicast_ttl() for more details.
756    ///
757    /// # Returns
758    ///
759    /// the multicast time-to-live setting on @self
760    #[doc(alias = "g_socket_get_multicast_ttl")]
761    #[doc(alias = "get_multicast_ttl")]
762    #[doc(alias = "multicast-ttl")]
763    fn multicast_ttl(&self) -> u32 {
764        unsafe { ffi::g_socket_get_multicast_ttl(self.as_ref().to_glib_none().0) }
765    }
766
767    /// Gets the value of an integer-valued option on @self, as with
768    /// getsockopt(). (If you need to fetch a  non-integer-valued option,
769    /// you will need to call getsockopt() directly.)
770    ///
771    /// The [`<gio/gnetworking.h>`](networking.html)
772    /// header pulls in system headers that will define most of the
773    /// standard/portable socket options. For unusual socket protocols or
774    /// platform-dependent options, you may need to include additional
775    /// headers.
776    ///
777    /// Note that even for socket options that are a single byte in size,
778    /// @value is still a pointer to a #gint variable, not a #guchar;
779    /// g_socket_get_option() will handle the conversion internally.
780    /// ## `level`
781    /// the "API level" of the option (eg, `SOL_SOCKET`)
782    /// ## `optname`
783    /// the "name" of the option (eg, `SO_BROADCAST`)
784    ///
785    /// # Returns
786    ///
787    /// success or failure. On failure, @error will be set, and
788    ///   the system error value (`errno` or WSAGetLastError()) will still
789    ///   be set to the result of the getsockopt() call.
790    ///
791    /// ## `value`
792    /// return location for the option value
793    #[doc(alias = "g_socket_get_option")]
794    #[doc(alias = "get_option")]
795    fn option(&self, level: i32, optname: i32) -> Result<i32, glib::Error> {
796        unsafe {
797            let mut value = std::mem::MaybeUninit::uninit();
798            let mut error = std::ptr::null_mut();
799            let is_ok = ffi::g_socket_get_option(
800                self.as_ref().to_glib_none().0,
801                level,
802                optname,
803                value.as_mut_ptr(),
804                &mut error,
805            );
806            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
807            if error.is_null() {
808                Ok(value.assume_init())
809            } else {
810                Err(from_glib_full(error))
811            }
812        }
813    }
814
815    /// Gets the socket protocol id the socket was created with.
816    /// In case the protocol is unknown, -1 is returned.
817    ///
818    /// # Returns
819    ///
820    /// a protocol id, or -1 if unknown
821    #[doc(alias = "g_socket_get_protocol")]
822    #[doc(alias = "get_protocol")]
823    fn protocol(&self) -> SocketProtocol {
824        unsafe { from_glib(ffi::g_socket_get_protocol(self.as_ref().to_glib_none().0)) }
825    }
826
827    /// Try to get the remote address of a connected socket. This is only
828    /// useful for connection oriented sockets that have been connected.
829    ///
830    /// # Returns
831    ///
832    /// a #GSocketAddress or [`None`] on error.
833    ///     Free the returned object with g_object_unref().
834    #[doc(alias = "g_socket_get_remote_address")]
835    #[doc(alias = "get_remote_address")]
836    #[doc(alias = "remote-address")]
837    fn remote_address(&self) -> Result<SocketAddress, glib::Error> {
838        unsafe {
839            let mut error = std::ptr::null_mut();
840            let ret = ffi::g_socket_get_remote_address(self.as_ref().to_glib_none().0, &mut error);
841            if error.is_null() {
842                Ok(from_glib_full(ret))
843            } else {
844                Err(from_glib_full(error))
845            }
846        }
847    }
848
849    /// Gets the socket type of the socket.
850    ///
851    /// # Returns
852    ///
853    /// a #GSocketType
854    #[doc(alias = "g_socket_get_socket_type")]
855    #[doc(alias = "get_socket_type")]
856    fn socket_type(&self) -> SocketType {
857        unsafe {
858            from_glib(ffi::g_socket_get_socket_type(
859                self.as_ref().to_glib_none().0,
860            ))
861        }
862    }
863
864    /// Gets the timeout setting of the socket. For details on this, see
865    /// g_socket_set_timeout().
866    ///
867    /// # Returns
868    ///
869    /// the timeout in seconds
870    #[doc(alias = "g_socket_get_timeout")]
871    #[doc(alias = "get_timeout")]
872    fn timeout(&self) -> u32 {
873        unsafe { ffi::g_socket_get_timeout(self.as_ref().to_glib_none().0) }
874    }
875
876    /// Gets the unicast time-to-live setting on @self; see
877    /// g_socket_set_ttl() for more details.
878    ///
879    /// # Returns
880    ///
881    /// the time-to-live setting on @self
882    #[doc(alias = "g_socket_get_ttl")]
883    #[doc(alias = "get_ttl")]
884    fn ttl(&self) -> u32 {
885        unsafe { ffi::g_socket_get_ttl(self.as_ref().to_glib_none().0) }
886    }
887
888    /// Checks whether a socket is closed.
889    ///
890    /// # Returns
891    ///
892    /// [`true`] if socket is closed, [`false`] otherwise
893    #[doc(alias = "g_socket_is_closed")]
894    fn is_closed(&self) -> bool {
895        unsafe { from_glib(ffi::g_socket_is_closed(self.as_ref().to_glib_none().0)) }
896    }
897
898    /// Check whether the socket is connected. This is only useful for
899    /// connection-oriented sockets.
900    ///
901    /// If using g_socket_shutdown(), this function will return [`true`] until the
902    /// socket has been shut down for reading and writing. If you do a non-blocking
903    /// connect, this function will not return [`true`] until after you call
904    /// g_socket_check_connect_result().
905    ///
906    /// # Returns
907    ///
908    /// [`true`] if socket is connected, [`false`] otherwise.
909    #[doc(alias = "g_socket_is_connected")]
910    fn is_connected(&self) -> bool {
911        unsafe { from_glib(ffi::g_socket_is_connected(self.as_ref().to_glib_none().0)) }
912    }
913
914    /// Registers @self to receive multicast messages sent to @group.
915    /// @self must be a [`SocketType::Datagram`][crate::SocketType::Datagram] socket, and must have
916    /// been bound to an appropriate interface and port with
917    /// g_socket_bind().
918    ///
919    /// If @iface is [`None`], the system will automatically pick an interface
920    /// to bind to based on @group.
921    ///
922    /// If @source_specific is [`true`], source-specific multicast as defined
923    /// in RFC 4604 is used. Note that on older platforms this may fail
924    /// with a [`IOErrorEnum::NotSupported`][crate::IOErrorEnum::NotSupported] error.
925    ///
926    /// To bind to a given source-specific multicast address, use
927    /// g_socket_join_multicast_group_ssm() instead.
928    /// ## `group`
929    /// a #GInetAddress specifying the group address to join.
930    /// ## `source_specific`
931    /// [`true`] if source-specific multicast should be used
932    /// ## `iface`
933    /// Name of the interface to use, or [`None`]
934    ///
935    /// # Returns
936    ///
937    /// [`true`] on success, [`false`] on error.
938    #[doc(alias = "g_socket_join_multicast_group")]
939    fn join_multicast_group(
940        &self,
941        group: &impl IsA<InetAddress>,
942        source_specific: bool,
943        iface: Option<&str>,
944    ) -> Result<(), glib::Error> {
945        unsafe {
946            let mut error = std::ptr::null_mut();
947            let is_ok = ffi::g_socket_join_multicast_group(
948                self.as_ref().to_glib_none().0,
949                group.as_ref().to_glib_none().0,
950                source_specific.into_glib(),
951                iface.to_glib_none().0,
952                &mut error,
953            );
954            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
955            if error.is_null() {
956                Ok(())
957            } else {
958                Err(from_glib_full(error))
959            }
960        }
961    }
962
963    /// Registers @self to receive multicast messages sent to @group.
964    /// @self must be a [`SocketType::Datagram`][crate::SocketType::Datagram] socket, and must have
965    /// been bound to an appropriate interface and port with
966    /// g_socket_bind().
967    ///
968    /// If @iface is [`None`], the system will automatically pick an interface
969    /// to bind to based on @group.
970    ///
971    /// If @source_specific is not [`None`], use source-specific multicast as
972    /// defined in RFC 4604. Note that on older platforms this may fail
973    /// with a [`IOErrorEnum::NotSupported`][crate::IOErrorEnum::NotSupported] error.
974    ///
975    /// Note that this function can be called multiple times for the same
976    /// @group with different @source_specific in order to receive multicast
977    /// packets from more than one source.
978    /// ## `group`
979    /// a #GInetAddress specifying the group address to join.
980    /// ## `source_specific`
981    /// a #GInetAddress specifying the
982    /// source-specific multicast address or [`None`] to ignore.
983    /// ## `iface`
984    /// Name of the interface to use, or [`None`]
985    ///
986    /// # Returns
987    ///
988    /// [`true`] on success, [`false`] on error.
989    #[doc(alias = "g_socket_join_multicast_group_ssm")]
990    fn join_multicast_group_ssm(
991        &self,
992        group: &impl IsA<InetAddress>,
993        source_specific: Option<&impl IsA<InetAddress>>,
994        iface: Option<&str>,
995    ) -> Result<(), glib::Error> {
996        unsafe {
997            let mut error = std::ptr::null_mut();
998            let is_ok = ffi::g_socket_join_multicast_group_ssm(
999                self.as_ref().to_glib_none().0,
1000                group.as_ref().to_glib_none().0,
1001                source_specific.map(|p| p.as_ref()).to_glib_none().0,
1002                iface.to_glib_none().0,
1003                &mut error,
1004            );
1005            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
1006            if error.is_null() {
1007                Ok(())
1008            } else {
1009                Err(from_glib_full(error))
1010            }
1011        }
1012    }
1013
1014    /// Removes @self from the multicast group defined by @group, @iface,
1015    /// and @source_specific (which must all have the same values they had
1016    /// when you joined the group).
1017    ///
1018    /// @self remains bound to its address and port, and can still receive
1019    /// unicast messages after calling this.
1020    ///
1021    /// To unbind to a given source-specific multicast address, use
1022    /// g_socket_leave_multicast_group_ssm() instead.
1023    /// ## `group`
1024    /// a #GInetAddress specifying the group address to leave.
1025    /// ## `source_specific`
1026    /// [`true`] if source-specific multicast was used
1027    /// ## `iface`
1028    /// Interface used
1029    ///
1030    /// # Returns
1031    ///
1032    /// [`true`] on success, [`false`] on error.
1033    #[doc(alias = "g_socket_leave_multicast_group")]
1034    fn leave_multicast_group(
1035        &self,
1036        group: &impl IsA<InetAddress>,
1037        source_specific: bool,
1038        iface: Option<&str>,
1039    ) -> Result<(), glib::Error> {
1040        unsafe {
1041            let mut error = std::ptr::null_mut();
1042            let is_ok = ffi::g_socket_leave_multicast_group(
1043                self.as_ref().to_glib_none().0,
1044                group.as_ref().to_glib_none().0,
1045                source_specific.into_glib(),
1046                iface.to_glib_none().0,
1047                &mut error,
1048            );
1049            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
1050            if error.is_null() {
1051                Ok(())
1052            } else {
1053                Err(from_glib_full(error))
1054            }
1055        }
1056    }
1057
1058    /// Removes @self from the multicast group defined by @group, @iface,
1059    /// and @source_specific (which must all have the same values they had
1060    /// when you joined the group).
1061    ///
1062    /// @self remains bound to its address and port, and can still receive
1063    /// unicast messages after calling this.
1064    /// ## `group`
1065    /// a #GInetAddress specifying the group address to leave.
1066    /// ## `source_specific`
1067    /// a #GInetAddress specifying the
1068    /// source-specific multicast address or [`None`] to ignore.
1069    /// ## `iface`
1070    /// Name of the interface to use, or [`None`]
1071    ///
1072    /// # Returns
1073    ///
1074    /// [`true`] on success, [`false`] on error.
1075    #[doc(alias = "g_socket_leave_multicast_group_ssm")]
1076    fn leave_multicast_group_ssm(
1077        &self,
1078        group: &impl IsA<InetAddress>,
1079        source_specific: Option<&impl IsA<InetAddress>>,
1080        iface: Option<&str>,
1081    ) -> Result<(), glib::Error> {
1082        unsafe {
1083            let mut error = std::ptr::null_mut();
1084            let is_ok = ffi::g_socket_leave_multicast_group_ssm(
1085                self.as_ref().to_glib_none().0,
1086                group.as_ref().to_glib_none().0,
1087                source_specific.map(|p| p.as_ref()).to_glib_none().0,
1088                iface.to_glib_none().0,
1089                &mut error,
1090            );
1091            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
1092            if error.is_null() {
1093                Ok(())
1094            } else {
1095                Err(from_glib_full(error))
1096            }
1097        }
1098    }
1099
1100    /// Marks the socket as a server socket, i.e. a socket that is used
1101    /// to accept incoming requests using g_socket_accept().
1102    ///
1103    /// Before calling this the socket must be bound to a local address using
1104    /// g_socket_bind().
1105    ///
1106    /// To set the maximum amount of outstanding clients, use
1107    /// g_socket_set_listen_backlog().
1108    ///
1109    /// # Returns
1110    ///
1111    /// [`true`] on success, [`false`] on error.
1112    #[doc(alias = "g_socket_listen")]
1113    fn listen(&self) -> Result<(), glib::Error> {
1114        unsafe {
1115            let mut error = std::ptr::null_mut();
1116            let is_ok = ffi::g_socket_listen(self.as_ref().to_glib_none().0, &mut error);
1117            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
1118            if error.is_null() {
1119                Ok(())
1120            } else {
1121                Err(from_glib_full(error))
1122            }
1123        }
1124    }
1125
1126    /// Sets the blocking mode of the socket. In blocking mode
1127    /// all operations (which don’t take an explicit blocking parameter) block until
1128    /// they succeed or there is an error. In
1129    /// non-blocking mode all functions return results immediately or
1130    /// with a [`IOErrorEnum::WouldBlock`][crate::IOErrorEnum::WouldBlock] error.
1131    ///
1132    /// All sockets are created in blocking mode. However, note that the
1133    /// platform level socket is always non-blocking, and blocking mode
1134    /// is a GSocket level feature.
1135    /// ## `blocking`
1136    /// Whether to use blocking I/O or not.
1137    #[doc(alias = "g_socket_set_blocking")]
1138    #[doc(alias = "blocking")]
1139    fn set_blocking(&self, blocking: bool) {
1140        unsafe {
1141            ffi::g_socket_set_blocking(self.as_ref().to_glib_none().0, blocking.into_glib());
1142        }
1143    }
1144
1145    /// Sets whether @self should allow sending to broadcast addresses.
1146    /// This is [`false`] by default.
1147    /// ## `broadcast`
1148    /// whether @self should allow sending to broadcast
1149    ///     addresses
1150    #[doc(alias = "g_socket_set_broadcast")]
1151    #[doc(alias = "broadcast")]
1152    fn set_broadcast(&self, broadcast: bool) {
1153        unsafe {
1154            ffi::g_socket_set_broadcast(self.as_ref().to_glib_none().0, broadcast.into_glib());
1155        }
1156    }
1157
1158    /// Sets or unsets the `SO_KEEPALIVE` flag on the underlying socket. When
1159    /// this flag is set on a socket, the system will attempt to verify that the
1160    /// remote socket endpoint is still present if a sufficiently long period of
1161    /// time passes with no data being exchanged. If the system is unable to
1162    /// verify the presence of the remote endpoint, it will automatically close
1163    /// the connection.
1164    ///
1165    /// This option is only functional on certain kinds of sockets. (Notably,
1166    /// [`SocketProtocol::Tcp`][crate::SocketProtocol::Tcp] sockets.)
1167    ///
1168    /// The exact time between pings is system- and protocol-dependent, but will
1169    /// normally be at least two hours. Most commonly, you would set this flag
1170    /// on a server socket if you want to allow clients to remain idle for long
1171    /// periods of time, but also want to ensure that connections are eventually
1172    /// garbage-collected if clients crash or become unreachable.
1173    /// ## `keepalive`
1174    /// Value for the keepalive flag
1175    #[doc(alias = "g_socket_set_keepalive")]
1176    #[doc(alias = "keepalive")]
1177    fn set_keepalive(&self, keepalive: bool) {
1178        unsafe {
1179            ffi::g_socket_set_keepalive(self.as_ref().to_glib_none().0, keepalive.into_glib());
1180        }
1181    }
1182
1183    /// Sets the maximum number of outstanding connections allowed
1184    /// when listening on this socket. If more clients than this are
1185    /// connecting to the socket and the application is not handling them
1186    /// on time then the new connections will be refused.
1187    ///
1188    /// Note that this must be called before g_socket_listen() and has no
1189    /// effect if called after that.
1190    /// ## `backlog`
1191    /// the maximum number of pending connections.
1192    #[doc(alias = "g_socket_set_listen_backlog")]
1193    #[doc(alias = "listen-backlog")]
1194    fn set_listen_backlog(&self, backlog: i32) {
1195        unsafe {
1196            ffi::g_socket_set_listen_backlog(self.as_ref().to_glib_none().0, backlog);
1197        }
1198    }
1199
1200    /// Sets whether outgoing multicast packets will be received by sockets
1201    /// listening on that multicast address on the same host. This is [`true`]
1202    /// by default.
1203    /// ## `loopback`
1204    /// whether @self should receive messages sent to its
1205    ///   multicast groups from the local host
1206    #[doc(alias = "g_socket_set_multicast_loopback")]
1207    #[doc(alias = "multicast-loopback")]
1208    fn set_multicast_loopback(&self, loopback: bool) {
1209        unsafe {
1210            ffi::g_socket_set_multicast_loopback(
1211                self.as_ref().to_glib_none().0,
1212                loopback.into_glib(),
1213            );
1214        }
1215    }
1216
1217    /// Sets the time-to-live for outgoing multicast datagrams on @self.
1218    /// By default, this is 1, meaning that multicast packets will not leave
1219    /// the local network.
1220    /// ## `ttl`
1221    /// the time-to-live value for all multicast datagrams on @self
1222    #[doc(alias = "g_socket_set_multicast_ttl")]
1223    #[doc(alias = "multicast-ttl")]
1224    fn set_multicast_ttl(&self, ttl: u32) {
1225        unsafe {
1226            ffi::g_socket_set_multicast_ttl(self.as_ref().to_glib_none().0, ttl);
1227        }
1228    }
1229
1230    /// Sets the value of an integer-valued option on @self, as with
1231    /// setsockopt(). (If you need to set a non-integer-valued option,
1232    /// you will need to call setsockopt() directly.)
1233    ///
1234    /// The [`<gio/gnetworking.h>`](networking.html)
1235    /// header pulls in system headers that will define most of the
1236    /// standard/portable socket options. For unusual socket protocols or
1237    /// platform-dependent options, you may need to include additional
1238    /// headers.
1239    /// ## `level`
1240    /// the "API level" of the option (eg, `SOL_SOCKET`)
1241    /// ## `optname`
1242    /// the "name" of the option (eg, `SO_BROADCAST`)
1243    /// ## `value`
1244    /// the value to set the option to
1245    ///
1246    /// # Returns
1247    ///
1248    /// success or failure. On failure, @error will be set, and
1249    ///   the system error value (`errno` or WSAGetLastError()) will still
1250    ///   be set to the result of the setsockopt() call.
1251    #[doc(alias = "g_socket_set_option")]
1252    fn set_option(&self, level: i32, optname: i32, value: i32) -> Result<(), glib::Error> {
1253        unsafe {
1254            let mut error = std::ptr::null_mut();
1255            let is_ok = ffi::g_socket_set_option(
1256                self.as_ref().to_glib_none().0,
1257                level,
1258                optname,
1259                value,
1260                &mut error,
1261            );
1262            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
1263            if error.is_null() {
1264                Ok(())
1265            } else {
1266                Err(from_glib_full(error))
1267            }
1268        }
1269    }
1270
1271    /// Sets the time in seconds after which I/O operations on @self will
1272    /// time out if they have not yet completed.
1273    ///
1274    /// On a blocking socket, this means that any blocking #GSocket
1275    /// operation will time out after @timeout seconds of inactivity,
1276    /// returning [`IOErrorEnum::TimedOut`][crate::IOErrorEnum::TimedOut].
1277    ///
1278    /// On a non-blocking socket, calls to g_socket_condition_wait() will
1279    /// also fail with [`IOErrorEnum::TimedOut`][crate::IOErrorEnum::TimedOut] after the given time. Sources
1280    /// created with g_socket_create_source() will trigger after
1281    /// @timeout seconds of inactivity, with the requested condition
1282    /// set, at which point calling g_socket_receive(), g_socket_send(),
1283    /// g_socket_check_connect_result(), etc, will fail with
1284    /// [`IOErrorEnum::TimedOut`][crate::IOErrorEnum::TimedOut].
1285    ///
1286    /// If @timeout is 0 (the default), operations will never time out
1287    /// on their own.
1288    ///
1289    /// Note that if an I/O operation is interrupted by a signal, this may
1290    /// cause the timeout to be reset.
1291    /// ## `timeout`
1292    /// the timeout for @self, in seconds, or 0 for none
1293    #[doc(alias = "g_socket_set_timeout")]
1294    #[doc(alias = "timeout")]
1295    fn set_timeout(&self, timeout: u32) {
1296        unsafe {
1297            ffi::g_socket_set_timeout(self.as_ref().to_glib_none().0, timeout);
1298        }
1299    }
1300
1301    /// Sets the time-to-live for outgoing unicast packets on @self.
1302    /// By default the platform-specific default value is used.
1303    /// ## `ttl`
1304    /// the time-to-live value for all unicast packets on @self
1305    #[doc(alias = "g_socket_set_ttl")]
1306    #[doc(alias = "ttl")]
1307    fn set_ttl(&self, ttl: u32) {
1308        unsafe {
1309            ffi::g_socket_set_ttl(self.as_ref().to_glib_none().0, ttl);
1310        }
1311    }
1312
1313    /// Shut down part or all of a full-duplex connection.
1314    ///
1315    /// If @shutdown_read is [`true`] then the receiving side of the connection
1316    /// is shut down, and further reading is disallowed.
1317    ///
1318    /// If @shutdown_write is [`true`] then the sending side of the connection
1319    /// is shut down, and further writing is disallowed.
1320    ///
1321    /// It is allowed for both @shutdown_read and @shutdown_write to be [`true`].
1322    ///
1323    /// One example where it is useful to shut down only one side of a connection is
1324    /// graceful disconnect for TCP connections where you close the sending side,
1325    /// then wait for the other side to close the connection, thus ensuring that the
1326    /// other side saw all sent data.
1327    /// ## `shutdown_read`
1328    /// whether to shut down the read side
1329    /// ## `shutdown_write`
1330    /// whether to shut down the write side
1331    ///
1332    /// # Returns
1333    ///
1334    /// [`true`] on success, [`false`] on error
1335    #[doc(alias = "g_socket_shutdown")]
1336    fn shutdown(&self, shutdown_read: bool, shutdown_write: bool) -> Result<(), glib::Error> {
1337        unsafe {
1338            let mut error = std::ptr::null_mut();
1339            let is_ok = ffi::g_socket_shutdown(
1340                self.as_ref().to_glib_none().0,
1341                shutdown_read.into_glib(),
1342                shutdown_write.into_glib(),
1343                &mut error,
1344            );
1345            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
1346            if error.is_null() {
1347                Ok(())
1348            } else {
1349                Err(from_glib_full(error))
1350            }
1351        }
1352    }
1353
1354    /// Checks if a socket is capable of speaking IPv4.
1355    ///
1356    /// IPv4 sockets are capable of speaking IPv4.  On some operating systems
1357    /// and under some combinations of circumstances IPv6 sockets are also
1358    /// capable of speaking IPv4.  See RFC 3493 section 3.7 for more
1359    /// information.
1360    ///
1361    /// No other types of sockets are currently considered as being capable
1362    /// of speaking IPv4.
1363    ///
1364    /// # Returns
1365    ///
1366    /// [`true`] if this socket can be used with IPv4.
1367    #[doc(alias = "g_socket_speaks_ipv4")]
1368    fn speaks_ipv4(&self) -> bool {
1369        unsafe { from_glib(ffi::g_socket_speaks_ipv4(self.as_ref().to_glib_none().0)) }
1370    }
1371
1372    /// The socket’s type.
1373    #[doc(alias = "type")]
1374    fn type_(&self) -> SocketType {
1375        ObjectExt::property(self.as_ref(), "type")
1376    }
1377
1378    #[doc(alias = "blocking")]
1379    fn connect_blocking_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
1380        unsafe extern "C" fn notify_blocking_trampoline<P: IsA<Socket>, F: Fn(&P) + 'static>(
1381            this: *mut ffi::GSocket,
1382            _param_spec: glib::ffi::gpointer,
1383            f: glib::ffi::gpointer,
1384        ) {
1385            let f: &F = &*(f as *const F);
1386            f(Socket::from_glib_borrow(this).unsafe_cast_ref())
1387        }
1388        unsafe {
1389            let f: Box_<F> = Box_::new(f);
1390            connect_raw(
1391                self.as_ptr() as *mut _,
1392                c"notify::blocking".as_ptr() as *const _,
1393                Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
1394                    notify_blocking_trampoline::<Self, F> as *const (),
1395                )),
1396                Box_::into_raw(f),
1397            )
1398        }
1399    }
1400
1401    #[doc(alias = "broadcast")]
1402    fn connect_broadcast_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
1403        unsafe extern "C" fn notify_broadcast_trampoline<P: IsA<Socket>, F: Fn(&P) + 'static>(
1404            this: *mut ffi::GSocket,
1405            _param_spec: glib::ffi::gpointer,
1406            f: glib::ffi::gpointer,
1407        ) {
1408            let f: &F = &*(f as *const F);
1409            f(Socket::from_glib_borrow(this).unsafe_cast_ref())
1410        }
1411        unsafe {
1412            let f: Box_<F> = Box_::new(f);
1413            connect_raw(
1414                self.as_ptr() as *mut _,
1415                c"notify::broadcast".as_ptr() as *const _,
1416                Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
1417                    notify_broadcast_trampoline::<Self, F> as *const (),
1418                )),
1419                Box_::into_raw(f),
1420            )
1421        }
1422    }
1423
1424    #[doc(alias = "keepalive")]
1425    fn connect_keepalive_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
1426        unsafe extern "C" fn notify_keepalive_trampoline<P: IsA<Socket>, F: Fn(&P) + 'static>(
1427            this: *mut ffi::GSocket,
1428            _param_spec: glib::ffi::gpointer,
1429            f: glib::ffi::gpointer,
1430        ) {
1431            let f: &F = &*(f as *const F);
1432            f(Socket::from_glib_borrow(this).unsafe_cast_ref())
1433        }
1434        unsafe {
1435            let f: Box_<F> = Box_::new(f);
1436            connect_raw(
1437                self.as_ptr() as *mut _,
1438                c"notify::keepalive".as_ptr() as *const _,
1439                Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
1440                    notify_keepalive_trampoline::<Self, F> as *const (),
1441                )),
1442                Box_::into_raw(f),
1443            )
1444        }
1445    }
1446
1447    #[doc(alias = "listen-backlog")]
1448    fn connect_listen_backlog_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
1449        unsafe extern "C" fn notify_listen_backlog_trampoline<
1450            P: IsA<Socket>,
1451            F: Fn(&P) + 'static,
1452        >(
1453            this: *mut ffi::GSocket,
1454            _param_spec: glib::ffi::gpointer,
1455            f: glib::ffi::gpointer,
1456        ) {
1457            let f: &F = &*(f as *const F);
1458            f(Socket::from_glib_borrow(this).unsafe_cast_ref())
1459        }
1460        unsafe {
1461            let f: Box_<F> = Box_::new(f);
1462            connect_raw(
1463                self.as_ptr() as *mut _,
1464                c"notify::listen-backlog".as_ptr() as *const _,
1465                Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
1466                    notify_listen_backlog_trampoline::<Self, F> as *const (),
1467                )),
1468                Box_::into_raw(f),
1469            )
1470        }
1471    }
1472
1473    #[doc(alias = "local-address")]
1474    fn connect_local_address_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
1475        unsafe extern "C" fn notify_local_address_trampoline<
1476            P: IsA<Socket>,
1477            F: Fn(&P) + 'static,
1478        >(
1479            this: *mut ffi::GSocket,
1480            _param_spec: glib::ffi::gpointer,
1481            f: glib::ffi::gpointer,
1482        ) {
1483            let f: &F = &*(f as *const F);
1484            f(Socket::from_glib_borrow(this).unsafe_cast_ref())
1485        }
1486        unsafe {
1487            let f: Box_<F> = Box_::new(f);
1488            connect_raw(
1489                self.as_ptr() as *mut _,
1490                c"notify::local-address".as_ptr() as *const _,
1491                Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
1492                    notify_local_address_trampoline::<Self, F> as *const (),
1493                )),
1494                Box_::into_raw(f),
1495            )
1496        }
1497    }
1498
1499    #[doc(alias = "multicast-loopback")]
1500    fn connect_multicast_loopback_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
1501        unsafe extern "C" fn notify_multicast_loopback_trampoline<
1502            P: IsA<Socket>,
1503            F: Fn(&P) + 'static,
1504        >(
1505            this: *mut ffi::GSocket,
1506            _param_spec: glib::ffi::gpointer,
1507            f: glib::ffi::gpointer,
1508        ) {
1509            let f: &F = &*(f as *const F);
1510            f(Socket::from_glib_borrow(this).unsafe_cast_ref())
1511        }
1512        unsafe {
1513            let f: Box_<F> = Box_::new(f);
1514            connect_raw(
1515                self.as_ptr() as *mut _,
1516                c"notify::multicast-loopback".as_ptr() as *const _,
1517                Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
1518                    notify_multicast_loopback_trampoline::<Self, F> as *const (),
1519                )),
1520                Box_::into_raw(f),
1521            )
1522        }
1523    }
1524
1525    #[doc(alias = "multicast-ttl")]
1526    fn connect_multicast_ttl_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
1527        unsafe extern "C" fn notify_multicast_ttl_trampoline<
1528            P: IsA<Socket>,
1529            F: Fn(&P) + 'static,
1530        >(
1531            this: *mut ffi::GSocket,
1532            _param_spec: glib::ffi::gpointer,
1533            f: glib::ffi::gpointer,
1534        ) {
1535            let f: &F = &*(f as *const F);
1536            f(Socket::from_glib_borrow(this).unsafe_cast_ref())
1537        }
1538        unsafe {
1539            let f: Box_<F> = Box_::new(f);
1540            connect_raw(
1541                self.as_ptr() as *mut _,
1542                c"notify::multicast-ttl".as_ptr() as *const _,
1543                Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
1544                    notify_multicast_ttl_trampoline::<Self, F> as *const (),
1545                )),
1546                Box_::into_raw(f),
1547            )
1548        }
1549    }
1550
1551    #[doc(alias = "remote-address")]
1552    fn connect_remote_address_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
1553        unsafe extern "C" fn notify_remote_address_trampoline<
1554            P: IsA<Socket>,
1555            F: Fn(&P) + 'static,
1556        >(
1557            this: *mut ffi::GSocket,
1558            _param_spec: glib::ffi::gpointer,
1559            f: glib::ffi::gpointer,
1560        ) {
1561            let f: &F = &*(f as *const F);
1562            f(Socket::from_glib_borrow(this).unsafe_cast_ref())
1563        }
1564        unsafe {
1565            let f: Box_<F> = Box_::new(f);
1566            connect_raw(
1567                self.as_ptr() as *mut _,
1568                c"notify::remote-address".as_ptr() as *const _,
1569                Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
1570                    notify_remote_address_trampoline::<Self, F> as *const (),
1571                )),
1572                Box_::into_raw(f),
1573            )
1574        }
1575    }
1576
1577    #[doc(alias = "timeout")]
1578    fn connect_timeout_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
1579        unsafe extern "C" fn notify_timeout_trampoline<P: IsA<Socket>, F: Fn(&P) + 'static>(
1580            this: *mut ffi::GSocket,
1581            _param_spec: glib::ffi::gpointer,
1582            f: glib::ffi::gpointer,
1583        ) {
1584            let f: &F = &*(f as *const F);
1585            f(Socket::from_glib_borrow(this).unsafe_cast_ref())
1586        }
1587        unsafe {
1588            let f: Box_<F> = Box_::new(f);
1589            connect_raw(
1590                self.as_ptr() as *mut _,
1591                c"notify::timeout".as_ptr() as *const _,
1592                Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
1593                    notify_timeout_trampoline::<Self, F> as *const (),
1594                )),
1595                Box_::into_raw(f),
1596            )
1597        }
1598    }
1599
1600    #[doc(alias = "ttl")]
1601    fn connect_ttl_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
1602        unsafe extern "C" fn notify_ttl_trampoline<P: IsA<Socket>, F: Fn(&P) + 'static>(
1603            this: *mut ffi::GSocket,
1604            _param_spec: glib::ffi::gpointer,
1605            f: glib::ffi::gpointer,
1606        ) {
1607            let f: &F = &*(f as *const F);
1608            f(Socket::from_glib_borrow(this).unsafe_cast_ref())
1609        }
1610        unsafe {
1611            let f: Box_<F> = Box_::new(f);
1612            connect_raw(
1613                self.as_ptr() as *mut _,
1614                c"notify::ttl".as_ptr() as *const _,
1615                Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
1616                    notify_ttl_trampoline::<Self, F> as *const (),
1617                )),
1618                Box_::into_raw(f),
1619            )
1620        }
1621    }
1622}
1623
1624impl<O: IsA<Socket>> SocketExt for O {}