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