1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
// This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT

use crate::{
    Cancellable, Credentials, DatagramBased, InetAddress, Initable, SocketAddress,
    SocketConnection, SocketFamily, SocketProtocol, SocketType,
};
use glib::{
    prelude::*,
    signal::{connect_raw, SignalHandlerId},
    translate::*,
};
use std::{boxed::Box as Box_, fmt, mem, mem::transmute, ptr};

glib::wrapper! {
    /// A [`Socket`][crate::Socket] is a low-level networking primitive. It is a more or less
    /// direct mapping of the BSD socket API in a portable GObject based API.
    /// It supports both the UNIX socket implementations and winsock2 on Windows.
    ///
    /// [`Socket`][crate::Socket] is the platform independent base upon which the higher level
    /// network primitives are based. Applications are not typically meant to
    /// use it directly, but rather through classes like [`SocketClient`][crate::SocketClient],
    /// [`SocketService`][crate::SocketService] and [`SocketConnection`][crate::SocketConnection]. However there may be cases where
    /// direct use of [`Socket`][crate::Socket] is useful.
    ///
    /// [`Socket`][crate::Socket] implements the [`Initable`][crate::Initable] interface, so if it is manually constructed
    /// by e.g. [`glib::Object::new()`][crate::glib::Object::new()] you must call [`InitableExt::init()`][crate::prelude::InitableExt::init()] and check the
    /// results before using the object. This is done automatically in
    /// [`new()`][Self::new()] and [`from_fd()`][Self::from_fd()], so these functions can return
    /// [`None`].
    ///
    /// Sockets operate in two general modes, blocking or non-blocking. When
    /// in blocking mode all operations (which don’t take an explicit blocking
    /// parameter) block until the requested operation
    /// is finished or there is an error. In non-blocking mode all calls that
    /// would block return immediately with a [`IOErrorEnum::WouldBlock`][crate::IOErrorEnum::WouldBlock] error.
    /// To know when a call would successfully run you can call [`SocketExt::condition_check()`][crate::prelude::SocketExt::condition_check()],
    /// or [`SocketExt::condition_wait()`][crate::prelude::SocketExt::condition_wait()]. You can also use `g_socket_create_source()` and
    /// attach it to a [`glib::MainContext`][crate::glib::MainContext] to get callbacks when I/O is possible.
    /// Note that all sockets are always set to non blocking mode in the system, and
    /// blocking mode is emulated in GSocket.
    ///
    /// When working in non-blocking mode applications should always be able to
    /// handle getting a [`IOErrorEnum::WouldBlock`][crate::IOErrorEnum::WouldBlock] error even when some other
    /// function said that I/O was possible. This can easily happen in case
    /// of a race condition in the application, but it can also happen for other
    /// reasons. For instance, on Windows a socket is always seen as writable
    /// until a write returns [`IOErrorEnum::WouldBlock`][crate::IOErrorEnum::WouldBlock].
    ///
    /// `GSockets` can be either connection oriented or datagram based.
    /// For connection oriented types you must first establish a connection by
    /// either connecting to an address or accepting a connection from another
    /// address. For connectionless socket types the target/source address is
    /// specified or received in each I/O operation.
    ///
    /// All socket file descriptors are set to be close-on-exec.
    ///
    /// Note that creating a [`Socket`][crate::Socket] causes the signal `SIGPIPE` to be
    /// ignored for the remainder of the program. If you are writing a
    /// command-line utility that uses [`Socket`][crate::Socket], you may need to take into
    /// account the fact that your program will not automatically be killed
    /// if it tries to write to `stdout` after it has been closed.
    ///
    /// Like most other APIs in GLib, [`Socket`][crate::Socket] is not inherently thread safe. To use
    /// a [`Socket`][crate::Socket] concurrently from multiple threads, you must implement your own
    /// locking.
    ///
    /// ## Properties
    ///
    ///
    /// #### `blocking`
    ///  Readable | Writeable
    ///
    ///
    /// #### `broadcast`
    ///  Whether the socket should allow sending to broadcast addresses.
    ///
    /// Readable | Writeable
    ///
    ///
    /// #### `family`
    ///  Readable | Writeable | Construct Only
    ///
    ///
    /// #### `fd`
    ///  Readable | Writeable | Construct Only
    ///
    ///
    /// #### `keepalive`
    ///  Readable | Writeable
    ///
    ///
    /// #### `listen-backlog`
    ///  Readable | Writeable
    ///
    ///
    /// #### `local-address`
    ///  Readable
    ///
    ///
    /// #### `multicast-loopback`
    ///  Whether outgoing multicast packets loop back to the local host.
    ///
    /// Readable | Writeable
    ///
    ///
    /// #### `multicast-ttl`
    ///  Time-to-live out outgoing multicast packets
    ///
    /// Readable | Writeable
    ///
    ///
    /// #### `protocol`
    ///  Readable | Writeable | Construct Only
    ///
    ///
    /// #### `remote-address`
    ///  Readable
    ///
    ///
    /// #### `timeout`
    ///  The timeout in seconds on socket I/O
    ///
    /// Readable | Writeable
    ///
    ///
    /// #### `ttl`
    ///  Time-to-live for outgoing unicast packets
    ///
    /// Readable | Writeable
    ///
    ///
    /// #### `type`
    ///  Readable | Writeable | Construct Only
    ///
    /// # Implements
    ///
    /// [`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]
    #[doc(alias = "GSocket")]
    pub struct Socket(Object<ffi::GSocket, ffi::GSocketClass>) @implements DatagramBased, Initable;

    match fn {
        type_ => || ffi::g_socket_get_type(),
    }
}

impl Socket {
    pub const NONE: Option<&'static Socket> = None;

    /// Creates a new [`Socket`][crate::Socket] with the defined family, type and protocol.
    /// If `protocol` is 0 ([`SocketProtocol::Default`][crate::SocketProtocol::Default]) the default protocol type
    /// for the family and type is used.
    ///
    /// The `protocol` is a family and type specific int that specifies what
    /// kind of protocol to use. [`SocketProtocol`][crate::SocketProtocol] lists several common ones.
    /// Many families only support one protocol, and use 0 for this, others
    /// support several and using 0 means to use the default protocol for
    /// the family and type.
    ///
    /// The protocol id is passed directly to the operating
    /// system, so you can use protocols not listed in [`SocketProtocol`][crate::SocketProtocol] if you
    /// know the protocol number used for it.
    /// ## `family`
    /// the socket family to use, e.g. [`SocketFamily::Ipv4`][crate::SocketFamily::Ipv4].
    /// ## `type_`
    /// the socket type to use.
    /// ## `protocol`
    /// the id of the protocol to use, or 0 for default.
    ///
    /// # Returns
    ///
    /// a [`Socket`][crate::Socket] or [`None`] on error.
    ///  Free the returned object with `g_object_unref()`.
    #[doc(alias = "g_socket_new")]
    pub fn new(
        family: SocketFamily,
        type_: SocketType,
        protocol: SocketProtocol,
    ) -> Result<Socket, glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let ret = ffi::g_socket_new(
                family.into_glib(),
                type_.into_glib(),
                protocol.into_glib(),
                &mut error,
            );
            if error.is_null() {
                Ok(from_glib_full(ret))
            } else {
                Err(from_glib_full(error))
            }
        }
    }
}

mod sealed {
    pub trait Sealed {}
    impl<T: super::IsA<super::Socket>> Sealed for T {}
}

/// Trait containing all [`struct@Socket`] methods.
///
/// # Implementors
///
/// [`Socket`][struct@crate::Socket]
pub trait SocketExt: IsA<Socket> + sealed::Sealed + 'static {
    /// Accept incoming connections on a connection-based socket. This removes
    /// the first outstanding connection request from the listening socket and
    /// creates a [`Socket`][crate::Socket] object for it.
    ///
    /// The `self` must be bound to a local address with [`bind()`][Self::bind()] and
    /// must be listening for incoming connections ([`listen()`][Self::listen()]).
    ///
    /// If there are no outstanding connections then the operation will block
    /// or return [`IOErrorEnum::WouldBlock`][crate::IOErrorEnum::WouldBlock] if non-blocking I/O is enabled.
    /// To be notified of an incoming connection, wait for the [`glib::IOCondition::IN`][crate::glib::IOCondition::IN] condition.
    /// ## `cancellable`
    /// a `GCancellable` or [`None`]
    ///
    /// # Returns
    ///
    /// a new [`Socket`][crate::Socket], or [`None`] on error.
    ///  Free the returned object with `g_object_unref()`.
    #[doc(alias = "g_socket_accept")]
    fn accept(&self, cancellable: Option<&impl IsA<Cancellable>>) -> Result<Socket, glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let ret = ffi::g_socket_accept(
                self.as_ref().to_glib_none().0,
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                &mut error,
            );
            if error.is_null() {
                Ok(from_glib_full(ret))
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// When a socket is created it is attached to an address family, but it
    /// doesn't have an address in this family. [`bind()`][Self::bind()] assigns the
    /// address (sometimes called name) of the socket.
    ///
    /// It is generally required to bind to a local address before you can
    /// receive connections. (See [`listen()`][Self::listen()] and [`accept()`][Self::accept()] ).
    /// In certain situations, you may also want to bind a socket that will be
    /// used to initiate connections, though this is not normally required.
    ///
    /// If `self` is a TCP socket, then `allow_reuse` controls the setting
    /// of the `SO_REUSEADDR` socket option; normally it should be [`true`] for
    /// server sockets (sockets that you will eventually call
    /// [`accept()`][Self::accept()] on), and [`false`] for client sockets. (Failing to
    /// set this flag on a server socket may cause [`bind()`][Self::bind()] to return
    /// [`IOErrorEnum::AddressInUse`][crate::IOErrorEnum::AddressInUse] if the server program is stopped and then
    /// immediately restarted.)
    ///
    /// If `self` is a UDP socket, then `allow_reuse` determines whether or
    /// not other UDP sockets can be bound to the same address at the same
    /// time. In particular, you can have several UDP sockets bound to the
    /// same address, and they will all receive all of the multicast and
    /// broadcast packets sent to that address. (The behavior of unicast
    /// UDP packets to an address with multiple listeners is not defined.)
    /// ## `address`
    /// a [`SocketAddress`][crate::SocketAddress] specifying the local address.
    /// ## `allow_reuse`
    /// whether to allow reusing this address
    ///
    /// # Returns
    ///
    /// [`true`] on success, [`false`] on error.
    #[doc(alias = "g_socket_bind")]
    fn bind(
        &self,
        address: &impl IsA<SocketAddress>,
        allow_reuse: bool,
    ) -> Result<(), glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let is_ok = ffi::g_socket_bind(
                self.as_ref().to_glib_none().0,
                address.as_ref().to_glib_none().0,
                allow_reuse.into_glib(),
                &mut error,
            );
            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
            if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Checks and resets the pending connect error for the socket.
    /// This is used to check for errors when [`connect()`][Self::connect()] is
    /// used in non-blocking mode.
    ///
    /// # Returns
    ///
    /// [`true`] if no error, [`false`] otherwise, setting `error` to the error
    #[doc(alias = "g_socket_check_connect_result")]
    fn check_connect_result(&self) -> Result<(), glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let is_ok =
                ffi::g_socket_check_connect_result(self.as_ref().to_glib_none().0, &mut error);
            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
            if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Closes the socket, shutting down any active connection.
    ///
    /// Closing a socket does not wait for all outstanding I/O operations
    /// to finish, so the caller should not rely on them to be guaranteed
    /// to complete even if the close returns with no error.
    ///
    /// Once the socket is closed, all other operations will return
    /// [`IOErrorEnum::Closed`][crate::IOErrorEnum::Closed]. Closing a socket multiple times will not
    /// return an error.
    ///
    /// Sockets will be automatically closed when the last reference
    /// is dropped, but you might want to call this function to make sure
    /// resources are released as early as possible.
    ///
    /// Beware that due to the way that TCP works, it is possible for
    /// recently-sent data to be lost if either you close a socket while the
    /// [`glib::IOCondition::IN`][crate::glib::IOCondition::IN] condition is set, or else if the remote connection tries to
    /// send something to you after you close the socket but before it has
    /// finished reading all of the data you sent. There is no easy generic
    /// way to avoid this problem; the easiest fix is to design the network
    /// protocol such that the client will never send data "out of turn".
    /// Another solution is for the server to half-close the connection by
    /// calling [`shutdown()`][Self::shutdown()] with only the `shutdown_write` flag set,
    /// and then wait for the client to notice this and close its side of the
    /// connection, after which the server can safely call [`close()`][Self::close()].
    /// (This is what [`TcpConnection`][crate::TcpConnection] does if you call
    /// [`TcpConnectionExt::set_graceful_disconnect()`][crate::prelude::TcpConnectionExt::set_graceful_disconnect()]. But of course, this
    /// only works if the client will close its connection after the server
    /// does.)
    ///
    /// # Returns
    ///
    /// [`true`] on success, [`false`] on error
    #[doc(alias = "g_socket_close")]
    fn close(&self) -> Result<(), glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let is_ok = ffi::g_socket_close(self.as_ref().to_glib_none().0, &mut error);
            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
            if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Checks on the readiness of `self` to perform operations.
    /// The operations specified in `condition` are checked for and masked
    /// against the currently-satisfied conditions on `self`. The result
    /// is returned.
    ///
    /// Note that on Windows, it is possible for an operation to return
    /// [`IOErrorEnum::WouldBlock`][crate::IOErrorEnum::WouldBlock] even immediately after
    /// [`condition_check()`][Self::condition_check()] has claimed that the socket is ready for
    /// writing. Rather than calling [`condition_check()`][Self::condition_check()] and then
    /// writing to the socket if it succeeds, it is generally better to
    /// simply try writing to the socket right away, and try again later if
    /// the initial attempt returns [`IOErrorEnum::WouldBlock`][crate::IOErrorEnum::WouldBlock].
    ///
    /// It is meaningless to specify [`glib::IOCondition::ERR`][crate::glib::IOCondition::ERR] or [`glib::IOCondition::HUP`][crate::glib::IOCondition::HUP] in condition;
    /// these conditions will always be set in the output if they are true.
    ///
    /// This call never blocks.
    /// ## `condition`
    /// a [`glib::IOCondition`][crate::glib::IOCondition] mask to check
    ///
    /// # Returns
    ///
    /// the [`glib::IOCondition`][crate::glib::IOCondition] mask of the current state
    #[doc(alias = "g_socket_condition_check")]
    fn condition_check(&self, condition: glib::IOCondition) -> glib::IOCondition {
        unsafe {
            from_glib(ffi::g_socket_condition_check(
                self.as_ref().to_glib_none().0,
                condition.into_glib(),
            ))
        }
    }

    /// Waits for up to `timeout_us` microseconds for `condition` to become true
    /// on `self`. If the condition is met, [`true`] is returned.
    ///
    /// If `cancellable` is cancelled before the condition is met, or if
    /// `timeout_us` (or the socket's [`timeout`][struct@crate::Socket#timeout]) is reached before the
    /// condition is met, then [`false`] is returned and `error`, if non-[`None`],
    /// is set to the appropriate value ([`IOErrorEnum::Cancelled`][crate::IOErrorEnum::Cancelled] or
    /// [`IOErrorEnum::TimedOut`][crate::IOErrorEnum::TimedOut]).
    ///
    /// If you don't want a timeout, use [`condition_wait()`][Self::condition_wait()].
    /// (Alternatively, you can pass -1 for `timeout_us`.)
    ///
    /// Note that although `timeout_us` is in microseconds for consistency with
    /// other GLib APIs, this function actually only has millisecond
    /// resolution, and the behavior is undefined if `timeout_us` is not an
    /// exact number of milliseconds.
    /// ## `condition`
    /// a [`glib::IOCondition`][crate::glib::IOCondition] mask to wait for
    /// ## `timeout_us`
    /// the maximum time (in microseconds) to wait, or -1
    /// ## `cancellable`
    /// a [`Cancellable`][crate::Cancellable], or [`None`]
    ///
    /// # Returns
    ///
    /// [`true`] if the condition was met, [`false`] otherwise
    #[doc(alias = "g_socket_condition_timed_wait")]
    fn condition_timed_wait(
        &self,
        condition: glib::IOCondition,
        timeout_us: i64,
        cancellable: Option<&impl IsA<Cancellable>>,
    ) -> Result<(), glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let is_ok = ffi::g_socket_condition_timed_wait(
                self.as_ref().to_glib_none().0,
                condition.into_glib(),
                timeout_us,
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                &mut error,
            );
            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
            if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Waits for `condition` to become true on `self`. When the condition
    /// is met, [`true`] is returned.
    ///
    /// If `cancellable` is cancelled before the condition is met, or if the
    /// socket has a timeout set and it is reached before the condition is
    /// met, then [`false`] is returned and `error`, if non-[`None`], is set to
    /// the appropriate value ([`IOErrorEnum::Cancelled`][crate::IOErrorEnum::Cancelled] or
    /// [`IOErrorEnum::TimedOut`][crate::IOErrorEnum::TimedOut]).
    ///
    /// See also [`condition_timed_wait()`][Self::condition_timed_wait()].
    /// ## `condition`
    /// a [`glib::IOCondition`][crate::glib::IOCondition] mask to wait for
    /// ## `cancellable`
    /// a [`Cancellable`][crate::Cancellable], or [`None`]
    ///
    /// # Returns
    ///
    /// [`true`] if the condition was met, [`false`] otherwise
    #[doc(alias = "g_socket_condition_wait")]
    fn condition_wait(
        &self,
        condition: glib::IOCondition,
        cancellable: Option<&impl IsA<Cancellable>>,
    ) -> Result<(), glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let is_ok = ffi::g_socket_condition_wait(
                self.as_ref().to_glib_none().0,
                condition.into_glib(),
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                &mut error,
            );
            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
            if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Connect the socket to the specified remote address.
    ///
    /// For connection oriented socket this generally means we attempt to make
    /// a connection to the `address`. For a connection-less socket it sets
    /// the default address for [`SocketExtManual::send()`][crate::prelude::SocketExtManual::send()] and discards all incoming datagrams
    /// from other sources.
    ///
    /// Generally connection oriented sockets can only connect once, but
    /// connection-less sockets can connect multiple times to change the
    /// default address.
    ///
    /// If the connect call needs to do network I/O it will block, unless
    /// non-blocking I/O is enabled. Then [`IOErrorEnum::Pending`][crate::IOErrorEnum::Pending] is returned
    /// and the user can be notified of the connection finishing by waiting
    /// for the G_IO_OUT condition. The result of the connection must then be
    /// checked with [`check_connect_result()`][Self::check_connect_result()].
    /// ## `address`
    /// a [`SocketAddress`][crate::SocketAddress] specifying the remote address.
    /// ## `cancellable`
    /// a `GCancellable` or [`None`]
    ///
    /// # Returns
    ///
    /// [`true`] if connected, [`false`] on error.
    #[doc(alias = "g_socket_connect")]
    fn connect(
        &self,
        address: &impl IsA<SocketAddress>,
        cancellable: Option<&impl IsA<Cancellable>>,
    ) -> Result<(), glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let is_ok = ffi::g_socket_connect(
                self.as_ref().to_glib_none().0,
                address.as_ref().to_glib_none().0,
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                &mut error,
            );
            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
            if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Creates a [`SocketConnection`][crate::SocketConnection] subclass of the right type for
    /// `self`.
    ///
    /// # Returns
    ///
    /// a [`SocketConnection`][crate::SocketConnection]
    #[doc(alias = "g_socket_connection_factory_create_connection")]
    fn connection_factory_create_connection(&self) -> SocketConnection {
        unsafe {
            from_glib_full(ffi::g_socket_connection_factory_create_connection(
                self.as_ref().to_glib_none().0,
            ))
        }
    }

    /// Get the amount of data pending in the OS input buffer, without blocking.
    ///
    /// If `self` is a UDP or SCTP socket, this will return the size of
    /// just the next packet, even if additional packets are buffered after
    /// that one.
    ///
    /// Note that on Windows, this function is rather inefficient in the
    /// UDP case, and so if you know any plausible upper bound on the size
    /// of the incoming packet, it is better to just do a
    /// [`SocketExtManual::receive()`][crate::prelude::SocketExtManual::receive()] with a buffer of that size, rather than calling
    /// [`available_bytes()`][Self::available_bytes()] first and then doing a receive of
    /// exactly the right size.
    ///
    /// # Returns
    ///
    /// the number of bytes that can be read from the socket
    /// without blocking or truncating, or -1 on error.
    #[doc(alias = "g_socket_get_available_bytes")]
    #[doc(alias = "get_available_bytes")]
    fn available_bytes(&self) -> isize {
        unsafe { ffi::g_socket_get_available_bytes(self.as_ref().to_glib_none().0) }
    }

    /// Gets the blocking mode of the socket. For details on blocking I/O,
    /// see [`set_blocking()`][Self::set_blocking()].
    ///
    /// # Returns
    ///
    /// [`true`] if blocking I/O is used, [`false`] otherwise.
    #[doc(alias = "g_socket_get_blocking")]
    #[doc(alias = "get_blocking")]
    fn is_blocking(&self) -> bool {
        unsafe { from_glib(ffi::g_socket_get_blocking(self.as_ref().to_glib_none().0)) }
    }

    /// Gets the broadcast setting on `self`; if [`true`],
    /// it is possible to send packets to broadcast
    /// addresses.
    ///
    /// # Returns
    ///
    /// the broadcast setting on `self`
    #[doc(alias = "g_socket_get_broadcast")]
    #[doc(alias = "get_broadcast")]
    fn is_broadcast(&self) -> bool {
        unsafe { from_glib(ffi::g_socket_get_broadcast(self.as_ref().to_glib_none().0)) }
    }

    /// Returns the credentials of the foreign process connected to this
    /// socket, if any (e.g. it is only supported for [`SocketFamily::Unix`][crate::SocketFamily::Unix]
    /// sockets).
    ///
    /// If this operation isn't supported on the OS, the method fails with
    /// the [`IOErrorEnum::NotSupported`][crate::IOErrorEnum::NotSupported] error. On Linux this is implemented
    /// by reading the `SO_PEERCRED` option on the underlying socket.
    ///
    /// This method can be expected to be available on the following platforms:
    ///
    /// - Linux since GLib 2.26
    /// - OpenBSD since GLib 2.30
    /// - Solaris, Illumos and OpenSolaris since GLib 2.40
    /// - NetBSD since GLib 2.42
    /// - macOS, tvOS, iOS since GLib 2.66
    ///
    /// Other ways to obtain credentials from a foreign peer includes the
    /// [`UnixCredentialsMessage`][crate::UnixCredentialsMessage] type and
    /// `g_unix_connection_send_credentials()` /
    /// `g_unix_connection_receive_credentials()` functions.
    ///
    /// # Returns
    ///
    /// [`None`] if `error` is set, otherwise a [`Credentials`][crate::Credentials] object
    /// that must be freed with `g_object_unref()`.
    #[doc(alias = "g_socket_get_credentials")]
    #[doc(alias = "get_credentials")]
    fn credentials(&self) -> Result<Credentials, glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let ret = ffi::g_socket_get_credentials(self.as_ref().to_glib_none().0, &mut error);
            if error.is_null() {
                Ok(from_glib_full(ret))
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Gets the socket family of the socket.
    ///
    /// # Returns
    ///
    /// a [`SocketFamily`][crate::SocketFamily]
    #[doc(alias = "g_socket_get_family")]
    #[doc(alias = "get_family")]
    fn family(&self) -> SocketFamily {
        unsafe { from_glib(ffi::g_socket_get_family(self.as_ref().to_glib_none().0)) }
    }

    /// Gets the keepalive mode of the socket. For details on this,
    /// see [`set_keepalive()`][Self::set_keepalive()].
    ///
    /// # Returns
    ///
    /// [`true`] if keepalive is active, [`false`] otherwise.
    #[doc(alias = "g_socket_get_keepalive")]
    #[doc(alias = "get_keepalive")]
    fn is_keepalive(&self) -> bool {
        unsafe { from_glib(ffi::g_socket_get_keepalive(self.as_ref().to_glib_none().0)) }
    }

    /// Gets the listen backlog setting of the socket. For details on this,
    /// see [`set_listen_backlog()`][Self::set_listen_backlog()].
    ///
    /// # Returns
    ///
    /// the maximum number of pending connections.
    #[doc(alias = "g_socket_get_listen_backlog")]
    #[doc(alias = "get_listen_backlog")]
    fn listen_backlog(&self) -> i32 {
        unsafe { ffi::g_socket_get_listen_backlog(self.as_ref().to_glib_none().0) }
    }

    /// Try to get the local address of a bound socket. This is only
    /// useful if the socket has been bound to a local address,
    /// either explicitly or implicitly when connecting.
    ///
    /// # Returns
    ///
    /// a [`SocketAddress`][crate::SocketAddress] or [`None`] on error.
    ///  Free the returned object with `g_object_unref()`.
    #[doc(alias = "g_socket_get_local_address")]
    #[doc(alias = "get_local_address")]
    fn local_address(&self) -> Result<SocketAddress, glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let ret = ffi::g_socket_get_local_address(self.as_ref().to_glib_none().0, &mut error);
            if error.is_null() {
                Ok(from_glib_full(ret))
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Gets the multicast loopback setting on `self`; if [`true`] (the
    /// default), outgoing multicast packets will be looped back to
    /// multicast listeners on the same host.
    ///
    /// # Returns
    ///
    /// the multicast loopback setting on `self`
    #[doc(alias = "g_socket_get_multicast_loopback")]
    #[doc(alias = "get_multicast_loopback")]
    fn is_multicast_loopback(&self) -> bool {
        unsafe {
            from_glib(ffi::g_socket_get_multicast_loopback(
                self.as_ref().to_glib_none().0,
            ))
        }
    }

    /// Gets the multicast time-to-live setting on `self`; see
    /// [`set_multicast_ttl()`][Self::set_multicast_ttl()] for more details.
    ///
    /// # Returns
    ///
    /// the multicast time-to-live setting on `self`
    #[doc(alias = "g_socket_get_multicast_ttl")]
    #[doc(alias = "get_multicast_ttl")]
    fn multicast_ttl(&self) -> u32 {
        unsafe { ffi::g_socket_get_multicast_ttl(self.as_ref().to_glib_none().0) }
    }

    /// Gets the value of an integer-valued option on `self`, as with
    /// `getsockopt()`. (If you need to fetch a non-integer-valued option,
    /// you will need to call `getsockopt()` directly.)
    ///
    /// The [<gio/gnetworking.h>][gio-gnetworking.h]
    /// header pulls in system headers that will define most of the
    /// standard/portable socket options. For unusual socket protocols or
    /// platform-dependent options, you may need to include additional
    /// headers.
    ///
    /// Note that even for socket options that are a single byte in size,
    /// `value` is still a pointer to a `gint` variable, not a `guchar`;
    /// [`option()`][Self::option()] will handle the conversion internally.
    /// ## `level`
    /// the "API level" of the option (eg, `SOL_SOCKET`)
    /// ## `optname`
    /// the "name" of the option (eg, `SO_BROADCAST`)
    ///
    /// # Returns
    ///
    /// success or failure. On failure, `error` will be set, and
    ///  the system error value (`errno` or WSAGetLastError()) will still
    ///  be set to the result of the `getsockopt()` call.
    ///
    /// ## `value`
    /// return location for the option value
    #[doc(alias = "g_socket_get_option")]
    #[doc(alias = "get_option")]
    fn option(&self, level: i32, optname: i32) -> Result<i32, glib::Error> {
        unsafe {
            let mut value = mem::MaybeUninit::uninit();
            let mut error = ptr::null_mut();
            let is_ok = ffi::g_socket_get_option(
                self.as_ref().to_glib_none().0,
                level,
                optname,
                value.as_mut_ptr(),
                &mut error,
            );
            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
            if error.is_null() {
                Ok(value.assume_init())
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Gets the socket protocol id the socket was created with.
    /// In case the protocol is unknown, -1 is returned.
    ///
    /// # Returns
    ///
    /// a protocol id, or -1 if unknown
    #[doc(alias = "g_socket_get_protocol")]
    #[doc(alias = "get_protocol")]
    fn protocol(&self) -> SocketProtocol {
        unsafe { from_glib(ffi::g_socket_get_protocol(self.as_ref().to_glib_none().0)) }
    }

    /// Try to get the remote address of a connected socket. This is only
    /// useful for connection oriented sockets that have been connected.
    ///
    /// # Returns
    ///
    /// a [`SocketAddress`][crate::SocketAddress] or [`None`] on error.
    ///  Free the returned object with `g_object_unref()`.
    #[doc(alias = "g_socket_get_remote_address")]
    #[doc(alias = "get_remote_address")]
    fn remote_address(&self) -> Result<SocketAddress, glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let ret = ffi::g_socket_get_remote_address(self.as_ref().to_glib_none().0, &mut error);
            if error.is_null() {
                Ok(from_glib_full(ret))
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Gets the socket type of the socket.
    ///
    /// # Returns
    ///
    /// a [`SocketType`][crate::SocketType]
    #[doc(alias = "g_socket_get_socket_type")]
    #[doc(alias = "get_socket_type")]
    fn socket_type(&self) -> SocketType {
        unsafe {
            from_glib(ffi::g_socket_get_socket_type(
                self.as_ref().to_glib_none().0,
            ))
        }
    }

    /// Gets the timeout setting of the socket. For details on this, see
    /// [`set_timeout()`][Self::set_timeout()].
    ///
    /// # Returns
    ///
    /// the timeout in seconds
    #[doc(alias = "g_socket_get_timeout")]
    #[doc(alias = "get_timeout")]
    fn timeout(&self) -> u32 {
        unsafe { ffi::g_socket_get_timeout(self.as_ref().to_glib_none().0) }
    }

    /// Gets the unicast time-to-live setting on `self`; see
    /// [`set_ttl()`][Self::set_ttl()] for more details.
    ///
    /// # Returns
    ///
    /// the time-to-live setting on `self`
    #[doc(alias = "g_socket_get_ttl")]
    #[doc(alias = "get_ttl")]
    fn ttl(&self) -> u32 {
        unsafe { ffi::g_socket_get_ttl(self.as_ref().to_glib_none().0) }
    }

    /// Checks whether a socket is closed.
    ///
    /// # Returns
    ///
    /// [`true`] if socket is closed, [`false`] otherwise
    #[doc(alias = "g_socket_is_closed")]
    fn is_closed(&self) -> bool {
        unsafe { from_glib(ffi::g_socket_is_closed(self.as_ref().to_glib_none().0)) }
    }

    /// Check whether the socket is connected. This is only useful for
    /// connection-oriented sockets.
    ///
    /// If using [`shutdown()`][Self::shutdown()], this function will return [`true`] until the
    /// socket has been shut down for reading and writing. If you do a non-blocking
    /// connect, this function will not return [`true`] until after you call
    /// [`check_connect_result()`][Self::check_connect_result()].
    ///
    /// # Returns
    ///
    /// [`true`] if socket is connected, [`false`] otherwise.
    #[doc(alias = "g_socket_is_connected")]
    fn is_connected(&self) -> bool {
        unsafe { from_glib(ffi::g_socket_is_connected(self.as_ref().to_glib_none().0)) }
    }

    /// Registers `self` to receive multicast messages sent to `group`.
    /// `self` must be a [`SocketType::Datagram`][crate::SocketType::Datagram] socket, and must have
    /// been bound to an appropriate interface and port with
    /// [`bind()`][Self::bind()].
    ///
    /// If `iface` is [`None`], the system will automatically pick an interface
    /// to bind to based on `group`.
    ///
    /// If `source_specific` is [`true`], source-specific multicast as defined
    /// in RFC 4604 is used. Note that on older platforms this may fail
    /// with a [`IOErrorEnum::NotSupported`][crate::IOErrorEnum::NotSupported] error.
    ///
    /// To bind to a given source-specific multicast address, use
    /// [`join_multicast_group_ssm()`][Self::join_multicast_group_ssm()] instead.
    /// ## `group`
    /// a [`InetAddress`][crate::InetAddress] specifying the group address to join.
    /// ## `source_specific`
    /// [`true`] if source-specific multicast should be used
    /// ## `iface`
    /// Name of the interface to use, or [`None`]
    ///
    /// # Returns
    ///
    /// [`true`] on success, [`false`] on error.
    #[doc(alias = "g_socket_join_multicast_group")]
    fn join_multicast_group(
        &self,
        group: &impl IsA<InetAddress>,
        source_specific: bool,
        iface: Option<&str>,
    ) -> Result<(), glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let is_ok = ffi::g_socket_join_multicast_group(
                self.as_ref().to_glib_none().0,
                group.as_ref().to_glib_none().0,
                source_specific.into_glib(),
                iface.to_glib_none().0,
                &mut error,
            );
            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
            if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Registers `self` to receive multicast messages sent to `group`.
    /// `self` must be a [`SocketType::Datagram`][crate::SocketType::Datagram] socket, and must have
    /// been bound to an appropriate interface and port with
    /// [`bind()`][Self::bind()].
    ///
    /// If `iface` is [`None`], the system will automatically pick an interface
    /// to bind to based on `group`.
    ///
    /// If `source_specific` is not [`None`], use source-specific multicast as
    /// defined in RFC 4604. Note that on older platforms this may fail
    /// with a [`IOErrorEnum::NotSupported`][crate::IOErrorEnum::NotSupported] error.
    ///
    /// Note that this function can be called multiple times for the same
    /// `group` with different `source_specific` in order to receive multicast
    /// packets from more than one source.
    /// ## `group`
    /// a [`InetAddress`][crate::InetAddress] specifying the group address to join.
    /// ## `source_specific`
    /// a [`InetAddress`][crate::InetAddress] specifying the
    /// source-specific multicast address or [`None`] to ignore.
    /// ## `iface`
    /// Name of the interface to use, or [`None`]
    ///
    /// # Returns
    ///
    /// [`true`] on success, [`false`] on error.
    #[doc(alias = "g_socket_join_multicast_group_ssm")]
    fn join_multicast_group_ssm(
        &self,
        group: &impl IsA<InetAddress>,
        source_specific: Option<&impl IsA<InetAddress>>,
        iface: Option<&str>,
    ) -> Result<(), glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let is_ok = ffi::g_socket_join_multicast_group_ssm(
                self.as_ref().to_glib_none().0,
                group.as_ref().to_glib_none().0,
                source_specific.map(|p| p.as_ref()).to_glib_none().0,
                iface.to_glib_none().0,
                &mut error,
            );
            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
            if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Removes `self` from the multicast group defined by `group`, `iface`,
    /// and `source_specific` (which must all have the same values they had
    /// when you joined the group).
    ///
    /// `self` remains bound to its address and port, and can still receive
    /// unicast messages after calling this.
    ///
    /// To unbind to a given source-specific multicast address, use
    /// [`leave_multicast_group_ssm()`][Self::leave_multicast_group_ssm()] instead.
    /// ## `group`
    /// a [`InetAddress`][crate::InetAddress] specifying the group address to leave.
    /// ## `source_specific`
    /// [`true`] if source-specific multicast was used
    /// ## `iface`
    /// Interface used
    ///
    /// # Returns
    ///
    /// [`true`] on success, [`false`] on error.
    #[doc(alias = "g_socket_leave_multicast_group")]
    fn leave_multicast_group(
        &self,
        group: &impl IsA<InetAddress>,
        source_specific: bool,
        iface: Option<&str>,
    ) -> Result<(), glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let is_ok = ffi::g_socket_leave_multicast_group(
                self.as_ref().to_glib_none().0,
                group.as_ref().to_glib_none().0,
                source_specific.into_glib(),
                iface.to_glib_none().0,
                &mut error,
            );
            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
            if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Removes `self` from the multicast group defined by `group`, `iface`,
    /// and `source_specific` (which must all have the same values they had
    /// when you joined the group).
    ///
    /// `self` remains bound to its address and port, and can still receive
    /// unicast messages after calling this.
    /// ## `group`
    /// a [`InetAddress`][crate::InetAddress] specifying the group address to leave.
    /// ## `source_specific`
    /// a [`InetAddress`][crate::InetAddress] specifying the
    /// source-specific multicast address or [`None`] to ignore.
    /// ## `iface`
    /// Name of the interface to use, or [`None`]
    ///
    /// # Returns
    ///
    /// [`true`] on success, [`false`] on error.
    #[doc(alias = "g_socket_leave_multicast_group_ssm")]
    fn leave_multicast_group_ssm(
        &self,
        group: &impl IsA<InetAddress>,
        source_specific: Option<&impl IsA<InetAddress>>,
        iface: Option<&str>,
    ) -> Result<(), glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let is_ok = ffi::g_socket_leave_multicast_group_ssm(
                self.as_ref().to_glib_none().0,
                group.as_ref().to_glib_none().0,
                source_specific.map(|p| p.as_ref()).to_glib_none().0,
                iface.to_glib_none().0,
                &mut error,
            );
            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
            if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Marks the socket as a server socket, i.e. a socket that is used
    /// to accept incoming requests using [`accept()`][Self::accept()].
    ///
    /// Before calling this the socket must be bound to a local address using
    /// [`bind()`][Self::bind()].
    ///
    /// To set the maximum amount of outstanding clients, use
    /// [`set_listen_backlog()`][Self::set_listen_backlog()].
    ///
    /// # Returns
    ///
    /// [`true`] on success, [`false`] on error.
    #[doc(alias = "g_socket_listen")]
    fn listen(&self) -> Result<(), glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let is_ok = ffi::g_socket_listen(self.as_ref().to_glib_none().0, &mut error);
            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
            if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Sets the blocking mode of the socket. In blocking mode
    /// all operations (which don’t take an explicit blocking parameter) block until
    /// they succeed or there is an error. In
    /// non-blocking mode all functions return results immediately or
    /// with a [`IOErrorEnum::WouldBlock`][crate::IOErrorEnum::WouldBlock] error.
    ///
    /// All sockets are created in blocking mode. However, note that the
    /// platform level socket is always non-blocking, and blocking mode
    /// is a GSocket level feature.
    /// ## `blocking`
    /// Whether to use blocking I/O or not.
    #[doc(alias = "g_socket_set_blocking")]
    fn set_blocking(&self, blocking: bool) {
        unsafe {
            ffi::g_socket_set_blocking(self.as_ref().to_glib_none().0, blocking.into_glib());
        }
    }

    /// Sets whether `self` should allow sending to broadcast addresses.
    /// This is [`false`] by default.
    /// ## `broadcast`
    /// whether `self` should allow sending to broadcast
    ///  addresses
    #[doc(alias = "g_socket_set_broadcast")]
    fn set_broadcast(&self, broadcast: bool) {
        unsafe {
            ffi::g_socket_set_broadcast(self.as_ref().to_glib_none().0, broadcast.into_glib());
        }
    }

    /// Sets or unsets the `SO_KEEPALIVE` flag on the underlying socket. When
    /// this flag is set on a socket, the system will attempt to verify that the
    /// remote socket endpoint is still present if a sufficiently long period of
    /// time passes with no data being exchanged. If the system is unable to
    /// verify the presence of the remote endpoint, it will automatically close
    /// the connection.
    ///
    /// This option is only functional on certain kinds of sockets. (Notably,
    /// [`SocketProtocol::Tcp`][crate::SocketProtocol::Tcp] sockets.)
    ///
    /// The exact time between pings is system- and protocol-dependent, but will
    /// normally be at least two hours. Most commonly, you would set this flag
    /// on a server socket if you want to allow clients to remain idle for long
    /// periods of time, but also want to ensure that connections are eventually
    /// garbage-collected if clients crash or become unreachable.
    /// ## `keepalive`
    /// Value for the keepalive flag
    #[doc(alias = "g_socket_set_keepalive")]
    fn set_keepalive(&self, keepalive: bool) {
        unsafe {
            ffi::g_socket_set_keepalive(self.as_ref().to_glib_none().0, keepalive.into_glib());
        }
    }

    /// Sets the maximum number of outstanding connections allowed
    /// when listening on this socket. If more clients than this are
    /// connecting to the socket and the application is not handling them
    /// on time then the new connections will be refused.
    ///
    /// Note that this must be called before [`listen()`][Self::listen()] and has no
    /// effect if called after that.
    /// ## `backlog`
    /// the maximum number of pending connections.
    #[doc(alias = "g_socket_set_listen_backlog")]
    fn set_listen_backlog(&self, backlog: i32) {
        unsafe {
            ffi::g_socket_set_listen_backlog(self.as_ref().to_glib_none().0, backlog);
        }
    }

    /// Sets whether outgoing multicast packets will be received by sockets
    /// listening on that multicast address on the same host. This is [`true`]
    /// by default.
    /// ## `loopback`
    /// whether `self` should receive messages sent to its
    ///  multicast groups from the local host
    #[doc(alias = "g_socket_set_multicast_loopback")]
    fn set_multicast_loopback(&self, loopback: bool) {
        unsafe {
            ffi::g_socket_set_multicast_loopback(
                self.as_ref().to_glib_none().0,
                loopback.into_glib(),
            );
        }
    }

    /// Sets the time-to-live for outgoing multicast datagrams on `self`.
    /// By default, this is 1, meaning that multicast packets will not leave
    /// the local network.
    /// ## `ttl`
    /// the time-to-live value for all multicast datagrams on `self`
    #[doc(alias = "g_socket_set_multicast_ttl")]
    fn set_multicast_ttl(&self, ttl: u32) {
        unsafe {
            ffi::g_socket_set_multicast_ttl(self.as_ref().to_glib_none().0, ttl);
        }
    }

    /// Sets the value of an integer-valued option on `self`, as with
    /// `setsockopt()`. (If you need to set a non-integer-valued option,
    /// you will need to call `setsockopt()` directly.)
    ///
    /// The [<gio/gnetworking.h>][gio-gnetworking.h]
    /// header pulls in system headers that will define most of the
    /// standard/portable socket options. For unusual socket protocols or
    /// platform-dependent options, you may need to include additional
    /// headers.
    /// ## `level`
    /// the "API level" of the option (eg, `SOL_SOCKET`)
    /// ## `optname`
    /// the "name" of the option (eg, `SO_BROADCAST`)
    /// ## `value`
    /// the value to set the option to
    ///
    /// # Returns
    ///
    /// success or failure. On failure, `error` will be set, and
    ///  the system error value (`errno` or WSAGetLastError()) will still
    ///  be set to the result of the `setsockopt()` call.
    #[doc(alias = "g_socket_set_option")]
    fn set_option(&self, level: i32, optname: i32, value: i32) -> Result<(), glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let is_ok = ffi::g_socket_set_option(
                self.as_ref().to_glib_none().0,
                level,
                optname,
                value,
                &mut error,
            );
            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
            if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Sets the time in seconds after which I/O operations on `self` will
    /// time out if they have not yet completed.
    ///
    /// On a blocking socket, this means that any blocking [`Socket`][crate::Socket]
    /// operation will time out after `timeout` seconds of inactivity,
    /// returning [`IOErrorEnum::TimedOut`][crate::IOErrorEnum::TimedOut].
    ///
    /// On a non-blocking socket, calls to [`condition_wait()`][Self::condition_wait()] will
    /// also fail with [`IOErrorEnum::TimedOut`][crate::IOErrorEnum::TimedOut] after the given time. Sources
    /// created with `g_socket_create_source()` will trigger after
    /// `timeout` seconds of inactivity, with the requested condition
    /// set, at which point calling [`SocketExtManual::receive()`][crate::prelude::SocketExtManual::receive()], [`SocketExtManual::send()`][crate::prelude::SocketExtManual::send()],
    /// [`check_connect_result()`][Self::check_connect_result()], etc, will fail with
    /// [`IOErrorEnum::TimedOut`][crate::IOErrorEnum::TimedOut].
    ///
    /// If `timeout` is 0 (the default), operations will never time out
    /// on their own.
    ///
    /// Note that if an I/O operation is interrupted by a signal, this may
    /// cause the timeout to be reset.
    /// ## `timeout`
    /// the timeout for `self`, in seconds, or 0 for none
    #[doc(alias = "g_socket_set_timeout")]
    fn set_timeout(&self, timeout: u32) {
        unsafe {
            ffi::g_socket_set_timeout(self.as_ref().to_glib_none().0, timeout);
        }
    }

    /// Sets the time-to-live for outgoing unicast packets on `self`.
    /// By default the platform-specific default value is used.
    /// ## `ttl`
    /// the time-to-live value for all unicast packets on `self`
    #[doc(alias = "g_socket_set_ttl")]
    fn set_ttl(&self, ttl: u32) {
        unsafe {
            ffi::g_socket_set_ttl(self.as_ref().to_glib_none().0, ttl);
        }
    }

    /// Shut down part or all of a full-duplex connection.
    ///
    /// If `shutdown_read` is [`true`] then the receiving side of the connection
    /// is shut down, and further reading is disallowed.
    ///
    /// If `shutdown_write` is [`true`] then the sending side of the connection
    /// is shut down, and further writing is disallowed.
    ///
    /// It is allowed for both `shutdown_read` and `shutdown_write` to be [`true`].
    ///
    /// One example where it is useful to shut down only one side of a connection is
    /// graceful disconnect for TCP connections where you close the sending side,
    /// then wait for the other side to close the connection, thus ensuring that the
    /// other side saw all sent data.
    /// ## `shutdown_read`
    /// whether to shut down the read side
    /// ## `shutdown_write`
    /// whether to shut down the write side
    ///
    /// # Returns
    ///
    /// [`true`] on success, [`false`] on error
    #[doc(alias = "g_socket_shutdown")]
    fn shutdown(&self, shutdown_read: bool, shutdown_write: bool) -> Result<(), glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let is_ok = ffi::g_socket_shutdown(
                self.as_ref().to_glib_none().0,
                shutdown_read.into_glib(),
                shutdown_write.into_glib(),
                &mut error,
            );
            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
            if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Checks if a socket is capable of speaking IPv4.
    ///
    /// IPv4 sockets are capable of speaking IPv4. On some operating systems
    /// and under some combinations of circumstances IPv6 sockets are also
    /// capable of speaking IPv4. See RFC 3493 section 3.7 for more
    /// information.
    ///
    /// No other types of sockets are currently considered as being capable
    /// of speaking IPv4.
    ///
    /// # Returns
    ///
    /// [`true`] if this socket can be used with IPv4.
    #[doc(alias = "g_socket_speaks_ipv4")]
    fn speaks_ipv4(&self) -> bool {
        unsafe { from_glib(ffi::g_socket_speaks_ipv4(self.as_ref().to_glib_none().0)) }
    }

    #[doc(alias = "type")]
    fn type_(&self) -> SocketType {
        ObjectExt::property(self.as_ref(), "type")
    }

    #[doc(alias = "blocking")]
    fn connect_blocking_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
        unsafe extern "C" fn notify_blocking_trampoline<P: IsA<Socket>, F: Fn(&P) + 'static>(
            this: *mut ffi::GSocket,
            _param_spec: glib::ffi::gpointer,
            f: glib::ffi::gpointer,
        ) {
            let f: &F = &*(f as *const F);
            f(Socket::from_glib_borrow(this).unsafe_cast_ref())
        }
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(
                self.as_ptr() as *mut _,
                b"notify::blocking\0".as_ptr() as *const _,
                Some(transmute::<_, unsafe extern "C" fn()>(
                    notify_blocking_trampoline::<Self, F> as *const (),
                )),
                Box_::into_raw(f),
            )
        }
    }

    #[doc(alias = "broadcast")]
    fn connect_broadcast_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
        unsafe extern "C" fn notify_broadcast_trampoline<P: IsA<Socket>, F: Fn(&P) + 'static>(
            this: *mut ffi::GSocket,
            _param_spec: glib::ffi::gpointer,
            f: glib::ffi::gpointer,
        ) {
            let f: &F = &*(f as *const F);
            f(Socket::from_glib_borrow(this).unsafe_cast_ref())
        }
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(
                self.as_ptr() as *mut _,
                b"notify::broadcast\0".as_ptr() as *const _,
                Some(transmute::<_, unsafe extern "C" fn()>(
                    notify_broadcast_trampoline::<Self, F> as *const (),
                )),
                Box_::into_raw(f),
            )
        }
    }

    #[doc(alias = "keepalive")]
    fn connect_keepalive_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
        unsafe extern "C" fn notify_keepalive_trampoline<P: IsA<Socket>, F: Fn(&P) + 'static>(
            this: *mut ffi::GSocket,
            _param_spec: glib::ffi::gpointer,
            f: glib::ffi::gpointer,
        ) {
            let f: &F = &*(f as *const F);
            f(Socket::from_glib_borrow(this).unsafe_cast_ref())
        }
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(
                self.as_ptr() as *mut _,
                b"notify::keepalive\0".as_ptr() as *const _,
                Some(transmute::<_, unsafe extern "C" fn()>(
                    notify_keepalive_trampoline::<Self, F> as *const (),
                )),
                Box_::into_raw(f),
            )
        }
    }

    #[doc(alias = "listen-backlog")]
    fn connect_listen_backlog_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
        unsafe extern "C" fn notify_listen_backlog_trampoline<
            P: IsA<Socket>,
            F: Fn(&P) + 'static,
        >(
            this: *mut ffi::GSocket,
            _param_spec: glib::ffi::gpointer,
            f: glib::ffi::gpointer,
        ) {
            let f: &F = &*(f as *const F);
            f(Socket::from_glib_borrow(this).unsafe_cast_ref())
        }
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(
                self.as_ptr() as *mut _,
                b"notify::listen-backlog\0".as_ptr() as *const _,
                Some(transmute::<_, unsafe extern "C" fn()>(
                    notify_listen_backlog_trampoline::<Self, F> as *const (),
                )),
                Box_::into_raw(f),
            )
        }
    }

    #[doc(alias = "local-address")]
    fn connect_local_address_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
        unsafe extern "C" fn notify_local_address_trampoline<
            P: IsA<Socket>,
            F: Fn(&P) + 'static,
        >(
            this: *mut ffi::GSocket,
            _param_spec: glib::ffi::gpointer,
            f: glib::ffi::gpointer,
        ) {
            let f: &F = &*(f as *const F);
            f(Socket::from_glib_borrow(this).unsafe_cast_ref())
        }
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(
                self.as_ptr() as *mut _,
                b"notify::local-address\0".as_ptr() as *const _,
                Some(transmute::<_, unsafe extern "C" fn()>(
                    notify_local_address_trampoline::<Self, F> as *const (),
                )),
                Box_::into_raw(f),
            )
        }
    }

    #[doc(alias = "multicast-loopback")]
    fn connect_multicast_loopback_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
        unsafe extern "C" fn notify_multicast_loopback_trampoline<
            P: IsA<Socket>,
            F: Fn(&P) + 'static,
        >(
            this: *mut ffi::GSocket,
            _param_spec: glib::ffi::gpointer,
            f: glib::ffi::gpointer,
        ) {
            let f: &F = &*(f as *const F);
            f(Socket::from_glib_borrow(this).unsafe_cast_ref())
        }
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(
                self.as_ptr() as *mut _,
                b"notify::multicast-loopback\0".as_ptr() as *const _,
                Some(transmute::<_, unsafe extern "C" fn()>(
                    notify_multicast_loopback_trampoline::<Self, F> as *const (),
                )),
                Box_::into_raw(f),
            )
        }
    }

    #[doc(alias = "multicast-ttl")]
    fn connect_multicast_ttl_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
        unsafe extern "C" fn notify_multicast_ttl_trampoline<
            P: IsA<Socket>,
            F: Fn(&P) + 'static,
        >(
            this: *mut ffi::GSocket,
            _param_spec: glib::ffi::gpointer,
            f: glib::ffi::gpointer,
        ) {
            let f: &F = &*(f as *const F);
            f(Socket::from_glib_borrow(this).unsafe_cast_ref())
        }
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(
                self.as_ptr() as *mut _,
                b"notify::multicast-ttl\0".as_ptr() as *const _,
                Some(transmute::<_, unsafe extern "C" fn()>(
                    notify_multicast_ttl_trampoline::<Self, F> as *const (),
                )),
                Box_::into_raw(f),
            )
        }
    }

    #[doc(alias = "remote-address")]
    fn connect_remote_address_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
        unsafe extern "C" fn notify_remote_address_trampoline<
            P: IsA<Socket>,
            F: Fn(&P) + 'static,
        >(
            this: *mut ffi::GSocket,
            _param_spec: glib::ffi::gpointer,
            f: glib::ffi::gpointer,
        ) {
            let f: &F = &*(f as *const F);
            f(Socket::from_glib_borrow(this).unsafe_cast_ref())
        }
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(
                self.as_ptr() as *mut _,
                b"notify::remote-address\0".as_ptr() as *const _,
                Some(transmute::<_, unsafe extern "C" fn()>(
                    notify_remote_address_trampoline::<Self, F> as *const (),
                )),
                Box_::into_raw(f),
            )
        }
    }

    #[doc(alias = "timeout")]
    fn connect_timeout_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
        unsafe extern "C" fn notify_timeout_trampoline<P: IsA<Socket>, F: Fn(&P) + 'static>(
            this: *mut ffi::GSocket,
            _param_spec: glib::ffi::gpointer,
            f: glib::ffi::gpointer,
        ) {
            let f: &F = &*(f as *const F);
            f(Socket::from_glib_borrow(this).unsafe_cast_ref())
        }
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(
                self.as_ptr() as *mut _,
                b"notify::timeout\0".as_ptr() as *const _,
                Some(transmute::<_, unsafe extern "C" fn()>(
                    notify_timeout_trampoline::<Self, F> as *const (),
                )),
                Box_::into_raw(f),
            )
        }
    }

    #[doc(alias = "ttl")]
    fn connect_ttl_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
        unsafe extern "C" fn notify_ttl_trampoline<P: IsA<Socket>, F: Fn(&P) + 'static>(
            this: *mut ffi::GSocket,
            _param_spec: glib::ffi::gpointer,
            f: glib::ffi::gpointer,
        ) {
            let f: &F = &*(f as *const F);
            f(Socket::from_glib_borrow(this).unsafe_cast_ref())
        }
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(
                self.as_ptr() as *mut _,
                b"notify::ttl\0".as_ptr() as *const _,
                Some(transmute::<_, unsafe extern "C" fn()>(
                    notify_ttl_trampoline::<Self, F> as *const (),
                )),
                Box_::into_raw(f),
            )
        }
    }
}

impl<O: IsA<Socket>> SocketExt for O {}

impl fmt::Display for Socket {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("Socket")
    }
}