carllerche/nix-rust — pull request #15 by ayosec (2014-10-30 13:20:02+00:00)
Title: Add getsockname(2) wrapper

Added a wrapper for `getsockname(2)` ([man page](http://man7.org/linux/man-pages/man2/getsockname.2.html)).

This function is essential if we want to bind a socket to the port 0, so the kernel will assign any available port.

The wrapper receives an argument with the `SockAddr` where the output of `getsockname` will be stored, and returns `true` when the size of expected structure matches the size of the argument. In practice, this is not an issue, since users will use the same `SockAddr` instance in both `bind` and `getsockname` functions.

Example:

```rust
// Initialize a sockaddr_in to address 127.0.0.1, port 0
let mut addr: sockaddr_in = unsafe { mem::zeroed() };
addr.sin_family = AF_INET as sa_family_t;
addr.sin_port = 0;
addr.sin_addr = in_addr { s_addr: 0x0100007fu32 };
let mut sock_addr = SockIpV4(addr);

// Create the socket and bind it to port 0
let socket = socket(AF_INET, SOCK_STREAM, SOCK_NONBLOCK).ok().expect("socket(...) failed");
bind(socket, &sock_addr).ok().expect("bound(...) failed");
listen(socket, 10).ok().expect("listen(...) failed");

// Get the assigned port to our socket
let ret = getsockname(socket, &mut sock_addr);
println!("getsockname(...) = {}, sock_addr = {}", ret, sock_addr);
```

Output:

getsockname(...) = Ok(true), sock_addr = 127.0.0.1:52094