Skip to content
This repository was archived by the owner on May 17, 2018. It is now read-only.

Commit e2c36c6

Browse files
committed
Implement UnixDatagram::connect()
1 parent 65cd124 commit e2c36c6

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

src/lib.rs

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -688,6 +688,22 @@ impl UnixDatagram {
688688
})
689689
}
690690

691+
/// Creates a Unix Datagram socket which is connected to specified addresss
692+
/// the socket is unnamed and similar to one created by `new()` except
693+
/// it will send message to the specified addresss *by default*
694+
pub fn connect<P: AsRef<Path>>(path: P) -> io::Result<UnixDatagram> {
695+
unsafe {
696+
let inner = try!(Inner::new(libc::SOCK_DGRAM));
697+
let (addr, len) = try!(sockaddr_un(path));
698+
699+
try!(cvt(libc::connect(inner.0, &addr as *const _ as *const _, len)));
700+
701+
Ok(UnixDatagram {
702+
inner: inner,
703+
})
704+
}
705+
}
706+
691707
/// Returns the address of this socket.
692708
pub fn local_addr(&self) -> io::Result<SocketAddr> {
693709
SocketAddr::new(|addr, len| unsafe { libc::getsockname(self.inner.0, addr, len) })
@@ -731,6 +747,21 @@ impl UnixDatagram {
731747
}
732748
}
733749

750+
/// Sends data on the socket to the default address.
751+
///
752+
/// Default address is set when socket was created by `connect()` constructor
753+
///
754+
/// On success, returns the number of bytes written.
755+
pub fn send(&self, buf: &[u8]) -> io::Result<usize> {
756+
unsafe {
757+
let count = try!(cvt_s(libc::send(self.inner.0,
758+
buf.as_ptr() as *const _,
759+
calc_len(buf),
760+
0)));
761+
Ok(count as usize)
762+
}
763+
}
764+
734765
/// Sets the read timeout for the socket.
735766
///
736767
/// If the provided value is `None`, then `recv_from` calls will block
@@ -1070,4 +1101,28 @@ mod test {
10701101
assert_eq!(addr.address(), AddressKind::Unnamed);
10711102
assert_eq!(msg, &buf[..]);
10721103
}
1104+
1105+
#[test]
1106+
fn test_connect_unix_datagram() {
1107+
let dir = or_panic!(TempDir::new("unix_socket"));
1108+
let path1 = dir.path().join("sock1");
1109+
1110+
let sock1 = or_panic!(UnixDatagram::bind(&path1));
1111+
let sock2 = or_panic!(UnixDatagram::connect(&path1));
1112+
1113+
// Check send()
1114+
let msg = b"hello there";
1115+
or_panic!(sock2.send(msg));
1116+
let mut buf = [0; 11];
1117+
let (usize, addr) = or_panic!(sock1.recv_from(&mut buf));
1118+
assert_eq!(usize, 11);
1119+
assert_eq!(addr.address(), AddressKind::Unnamed);
1120+
assert_eq!(msg, &buf[..]);
1121+
1122+
// Send to should still work too
1123+
let msg = b"hello world";
1124+
or_panic!(sock2.send_to(msg, &path1));
1125+
or_panic!(sock1.recv_from(&mut buf));
1126+
assert_eq!(msg, &buf[..]);
1127+
}
10731128
}

0 commit comments

Comments
 (0)