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 Cancellable, Credentials, DatagramBased, InetAddress, Initable, SocketAddress,
7 SocketConnection, SocketFamily, SocketProtocol, SocketType, ffi,
8};
9use glib::{
10 prelude::*,
11 signal::{SignalHandlerId, connect_raw},
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 unsafe {
1386 let f: &F = &*(f as *const F);
1387 f(Socket::from_glib_borrow(this).unsafe_cast_ref())
1388 }
1389 }
1390 unsafe {
1391 let f: Box_<F> = Box_::new(f);
1392 connect_raw(
1393 self.as_ptr() as *mut _,
1394 c"notify::blocking".as_ptr() as *const _,
1395 Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
1396 notify_blocking_trampoline::<Self, F> as *const (),
1397 )),
1398 Box_::into_raw(f),
1399 )
1400 }
1401 }
1402
1403 #[doc(alias = "broadcast")]
1404 fn connect_broadcast_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
1405 unsafe extern "C" fn notify_broadcast_trampoline<P: IsA<Socket>, F: Fn(&P) + 'static>(
1406 this: *mut ffi::GSocket,
1407 _param_spec: glib::ffi::gpointer,
1408 f: glib::ffi::gpointer,
1409 ) {
1410 unsafe {
1411 let f: &F = &*(f as *const F);
1412 f(Socket::from_glib_borrow(this).unsafe_cast_ref())
1413 }
1414 }
1415 unsafe {
1416 let f: Box_<F> = Box_::new(f);
1417 connect_raw(
1418 self.as_ptr() as *mut _,
1419 c"notify::broadcast".as_ptr() as *const _,
1420 Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
1421 notify_broadcast_trampoline::<Self, F> as *const (),
1422 )),
1423 Box_::into_raw(f),
1424 )
1425 }
1426 }
1427
1428 #[doc(alias = "keepalive")]
1429 fn connect_keepalive_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
1430 unsafe extern "C" fn notify_keepalive_trampoline<P: IsA<Socket>, F: Fn(&P) + 'static>(
1431 this: *mut ffi::GSocket,
1432 _param_spec: glib::ffi::gpointer,
1433 f: glib::ffi::gpointer,
1434 ) {
1435 unsafe {
1436 let f: &F = &*(f as *const F);
1437 f(Socket::from_glib_borrow(this).unsafe_cast_ref())
1438 }
1439 }
1440 unsafe {
1441 let f: Box_<F> = Box_::new(f);
1442 connect_raw(
1443 self.as_ptr() as *mut _,
1444 c"notify::keepalive".as_ptr() as *const _,
1445 Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
1446 notify_keepalive_trampoline::<Self, F> as *const (),
1447 )),
1448 Box_::into_raw(f),
1449 )
1450 }
1451 }
1452
1453 #[doc(alias = "listen-backlog")]
1454 fn connect_listen_backlog_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
1455 unsafe extern "C" fn notify_listen_backlog_trampoline<
1456 P: IsA<Socket>,
1457 F: Fn(&P) + 'static,
1458 >(
1459 this: *mut ffi::GSocket,
1460 _param_spec: glib::ffi::gpointer,
1461 f: glib::ffi::gpointer,
1462 ) {
1463 unsafe {
1464 let f: &F = &*(f as *const F);
1465 f(Socket::from_glib_borrow(this).unsafe_cast_ref())
1466 }
1467 }
1468 unsafe {
1469 let f: Box_<F> = Box_::new(f);
1470 connect_raw(
1471 self.as_ptr() as *mut _,
1472 c"notify::listen-backlog".as_ptr() as *const _,
1473 Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
1474 notify_listen_backlog_trampoline::<Self, F> as *const (),
1475 )),
1476 Box_::into_raw(f),
1477 )
1478 }
1479 }
1480
1481 #[doc(alias = "local-address")]
1482 fn connect_local_address_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
1483 unsafe extern "C" fn notify_local_address_trampoline<
1484 P: IsA<Socket>,
1485 F: Fn(&P) + 'static,
1486 >(
1487 this: *mut ffi::GSocket,
1488 _param_spec: glib::ffi::gpointer,
1489 f: glib::ffi::gpointer,
1490 ) {
1491 unsafe {
1492 let f: &F = &*(f as *const F);
1493 f(Socket::from_glib_borrow(this).unsafe_cast_ref())
1494 }
1495 }
1496 unsafe {
1497 let f: Box_<F> = Box_::new(f);
1498 connect_raw(
1499 self.as_ptr() as *mut _,
1500 c"notify::local-address".as_ptr() as *const _,
1501 Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
1502 notify_local_address_trampoline::<Self, F> as *const (),
1503 )),
1504 Box_::into_raw(f),
1505 )
1506 }
1507 }
1508
1509 #[doc(alias = "multicast-loopback")]
1510 fn connect_multicast_loopback_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
1511 unsafe extern "C" fn notify_multicast_loopback_trampoline<
1512 P: IsA<Socket>,
1513 F: Fn(&P) + 'static,
1514 >(
1515 this: *mut ffi::GSocket,
1516 _param_spec: glib::ffi::gpointer,
1517 f: glib::ffi::gpointer,
1518 ) {
1519 unsafe {
1520 let f: &F = &*(f as *const F);
1521 f(Socket::from_glib_borrow(this).unsafe_cast_ref())
1522 }
1523 }
1524 unsafe {
1525 let f: Box_<F> = Box_::new(f);
1526 connect_raw(
1527 self.as_ptr() as *mut _,
1528 c"notify::multicast-loopback".as_ptr() as *const _,
1529 Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
1530 notify_multicast_loopback_trampoline::<Self, F> as *const (),
1531 )),
1532 Box_::into_raw(f),
1533 )
1534 }
1535 }
1536
1537 #[doc(alias = "multicast-ttl")]
1538 fn connect_multicast_ttl_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
1539 unsafe extern "C" fn notify_multicast_ttl_trampoline<
1540 P: IsA<Socket>,
1541 F: Fn(&P) + 'static,
1542 >(
1543 this: *mut ffi::GSocket,
1544 _param_spec: glib::ffi::gpointer,
1545 f: glib::ffi::gpointer,
1546 ) {
1547 unsafe {
1548 let f: &F = &*(f as *const F);
1549 f(Socket::from_glib_borrow(this).unsafe_cast_ref())
1550 }
1551 }
1552 unsafe {
1553 let f: Box_<F> = Box_::new(f);
1554 connect_raw(
1555 self.as_ptr() as *mut _,
1556 c"notify::multicast-ttl".as_ptr() as *const _,
1557 Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
1558 notify_multicast_ttl_trampoline::<Self, F> as *const (),
1559 )),
1560 Box_::into_raw(f),
1561 )
1562 }
1563 }
1564
1565 #[doc(alias = "remote-address")]
1566 fn connect_remote_address_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
1567 unsafe extern "C" fn notify_remote_address_trampoline<
1568 P: IsA<Socket>,
1569 F: Fn(&P) + 'static,
1570 >(
1571 this: *mut ffi::GSocket,
1572 _param_spec: glib::ffi::gpointer,
1573 f: glib::ffi::gpointer,
1574 ) {
1575 unsafe {
1576 let f: &F = &*(f as *const F);
1577 f(Socket::from_glib_borrow(this).unsafe_cast_ref())
1578 }
1579 }
1580 unsafe {
1581 let f: Box_<F> = Box_::new(f);
1582 connect_raw(
1583 self.as_ptr() as *mut _,
1584 c"notify::remote-address".as_ptr() as *const _,
1585 Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
1586 notify_remote_address_trampoline::<Self, F> as *const (),
1587 )),
1588 Box_::into_raw(f),
1589 )
1590 }
1591 }
1592
1593 #[doc(alias = "timeout")]
1594 fn connect_timeout_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
1595 unsafe extern "C" fn notify_timeout_trampoline<P: IsA<Socket>, F: Fn(&P) + 'static>(
1596 this: *mut ffi::GSocket,
1597 _param_spec: glib::ffi::gpointer,
1598 f: glib::ffi::gpointer,
1599 ) {
1600 unsafe {
1601 let f: &F = &*(f as *const F);
1602 f(Socket::from_glib_borrow(this).unsafe_cast_ref())
1603 }
1604 }
1605 unsafe {
1606 let f: Box_<F> = Box_::new(f);
1607 connect_raw(
1608 self.as_ptr() as *mut _,
1609 c"notify::timeout".as_ptr() as *const _,
1610 Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
1611 notify_timeout_trampoline::<Self, F> as *const (),
1612 )),
1613 Box_::into_raw(f),
1614 )
1615 }
1616 }
1617
1618 #[doc(alias = "ttl")]
1619 fn connect_ttl_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
1620 unsafe extern "C" fn notify_ttl_trampoline<P: IsA<Socket>, F: Fn(&P) + 'static>(
1621 this: *mut ffi::GSocket,
1622 _param_spec: glib::ffi::gpointer,
1623 f: glib::ffi::gpointer,
1624 ) {
1625 unsafe {
1626 let f: &F = &*(f as *const F);
1627 f(Socket::from_glib_borrow(this).unsafe_cast_ref())
1628 }
1629 }
1630 unsafe {
1631 let f: Box_<F> = Box_::new(f);
1632 connect_raw(
1633 self.as_ptr() as *mut _,
1634 c"notify::ttl".as_ptr() as *const _,
1635 Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
1636 notify_ttl_trampoline::<Self, F> as *const (),
1637 )),
1638 Box_::into_raw(f),
1639 )
1640 }
1641 }
1642}
1643
1644impl<O: IsA<Socket>> SocketExt for O {}