@@ -43,7 +43,9 @@ impl Socket {
43
43
/// This function is only available on Unix when the `pair` feature is
44
44
/// enabled.
45
45
#[ cfg( all( unix, feature = "pair" ) ) ]
46
- pub fn pair ( domain : Domain , type_ : Type , protocol : Option < Protocol > ) -> io:: Result < ( Socket , Socket ) > {
46
+ pub fn pair ( domain : Domain ,
47
+ type_ : Type ,
48
+ protocol : Option < Protocol > ) -> io:: Result < ( Socket , Socket ) > {
47
49
let protocol = protocol. map ( |p| p. 0 ) . unwrap_or ( 0 ) ;
48
50
let sockets = sys:: Socket :: pair ( domain. 0 , type_. 0 , protocol) ?;
49
51
Ok ( ( Socket { inner : sockets. 0 } , Socket { inner : sockets. 1 } ) )
@@ -640,6 +642,15 @@ impl Domain {
640
642
pub fn ipv6 ( ) -> Domain {
641
643
Domain ( c:: AF_INET6 )
642
644
}
645
+
646
+ /// Domain for Unix socket communication, corresponding to `AF_UNIX`.
647
+ ///
648
+ /// This function is only available on Unix when the `unix` feature is
649
+ /// activated.
650
+ #[ cfg( all( unix, feature = "unix" ) ) ]
651
+ pub fn unix ( ) -> Domain {
652
+ Domain ( c:: AF_UNIX )
653
+ }
643
654
}
644
655
645
656
impl From < i32 > for Domain {
@@ -734,4 +745,37 @@ mod test {
734
745
let socket = Socket :: new ( Domain :: ipv4 ( ) , Type :: stream ( ) , None ) . unwrap ( ) ;
735
746
socket. connect_timeout ( & addr, Duration :: from_millis ( 250 ) ) . unwrap ( ) ;
736
747
}
748
+
749
+ #[ test]
750
+ #[ cfg( all( unix, feature = "pair" , feature = "unix" ) ) ]
751
+ fn pair ( ) {
752
+ let ( mut a, mut b) = Socket :: pair ( Domain :: unix ( ) , Type :: stream ( ) , None ) . unwrap ( ) ;
753
+ a. write_all ( b"hello world" ) . unwrap ( ) ;
754
+ let mut buf = [ 0 ; 11 ] ;
755
+ b. read_exact ( & mut buf) . unwrap ( ) ;
756
+ assert_eq ! ( buf, & b"hello world" [ ..] ) ;
757
+ }
758
+
759
+ #[ test]
760
+ #[ cfg( all( unix, feature = "unix" ) ) ]
761
+ fn unix ( ) {
762
+ use tempdir:: TempDir ;
763
+
764
+ let dir = TempDir :: new ( "unix" ) . unwrap ( ) ;
765
+ let addr = SockAddr :: unix ( dir. path ( ) . join ( "sock" ) ) . unwrap ( ) ;
766
+
767
+ let listener = Socket :: new ( Domain :: unix ( ) , Type :: stream ( ) , None ) . unwrap ( ) ;
768
+ listener. bind ( & addr) . unwrap ( ) ;
769
+ listener. listen ( 10 ) . unwrap ( ) ;
770
+
771
+ let mut a = Socket :: new ( Domain :: unix ( ) , Type :: stream ( ) , None ) . unwrap ( ) ;
772
+ a. connect ( & addr) . unwrap ( ) ;
773
+
774
+ let mut b = listener. accept ( ) . unwrap ( ) . 0 ;
775
+
776
+ a. write_all ( b"hello world" ) . unwrap ( ) ;
777
+ let mut buf = [ 0 ; 11 ] ;
778
+ b. read_exact ( & mut buf) . unwrap ( ) ;
779
+ assert_eq ! ( buf, & b"hello world" [ ..] ) ;
780
+ }
737
781
}
0 commit comments