Skip to content

Instantly share code, notes, and snippets.

@nuno1212s
Created June 26, 2022 19:11
Show Gist options
  • Save nuno1212s/6560c72477d8356908b2de73ad34baf6 to your computer and use it in GitHub Desktop.
Save nuno1212s/6560c72477d8356908b2de73ad34baf6 to your computer and use it in GitHub Desktop.
pub fn bind_and_connect<A: Into<SocketAddr>>(addr: A, bind_ip: IpAddr) -> io::Result<Socket> {
let addr = addr.into();
let host = match SockaddrIn::from_str(match bind_ip {
IpAddr::V4(ipv4) => {
format!("{}:{}", ipv4, addr.port())
}
IpAddr::V6(_) => {
return Err(std::io::Error::from(ErrorKind::Unsupported));
}
}.as_str()) {
Ok(host) => {
host
}
Err(_) => {
return Err(std::io::Error::from(ErrorKind::AddrNotAvailable))
}
};
let raw_fd = match nix::sys::socket::socket(AddressFamily::Inet, SockType::Stream, SockFlag::empty(), None) {
Ok(raw_fd) => {
raw_fd
}
Err(errno) => {
return Err(io::Error::from(errno));
}
};
match nix::sys::socket::bind(raw_fd, &host) {
Err(errno) => {
return Err(io::Error::from(errno));
}
_ => {}
};
let connecting_ip = SockaddrIn::from(match addr {
SocketAddr::V4(v4) => {v4}
SocketAddr::V6(_) => {
return Err(std::io::Error::from(ErrorKind::Unsupported));
}
});
match nix::sys::socket::connect(raw_fd, &connecting_ip) {
Ok(_) => {}
Err(errno) => {
return Err(std::io::Error::from(errno));
}
};
let tcp_stream = unsafe {
TcpStream::from_raw_fd(raw_fd)
};
Ok(Socket::new(tcp_stream))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment