Sponge
CS144's user-space TCP library
tcp_native.cc
Go to the documentation of this file.
2 
3 #include <cstdlib>
4 #include <cstring>
5 #include <iostream>
6 
7 using namespace std;
8 
9 void show_usage(const char *argv0) {
10  cerr << "Usage: " << argv0 << " [-l] <host> <port>\n\n"
11  << " -l specifies listen mode; <host>:<port> is the listening address." << endl;
12 }
13 
14 int main(int argc, char **argv) {
15  try {
16  bool server_mode = false;
17  if (argc < 3 || ((server_mode = (strncmp("-l", argv[1], 3) == 0)) && argc < 4)) {
18  show_usage(argv[0]);
19  return EXIT_FAILURE;
20  }
21 
22  // in client mode, connect; in server mode, accept exactly one connection
23  auto socket = [&] {
24  if (server_mode) {
25  TCPSocket listening_socket; // create a TCP socket
26  listening_socket.set_reuseaddr(); // reuse the server's address as soon as the program quits
27  listening_socket.bind({argv[2], argv[3]}); // bind to specified address
28  listening_socket.listen(); // mark the socket as listening for incoming connections
29  return listening_socket.accept(); // accept exactly one connection
30  }
31  TCPSocket connecting_socket;
32  connecting_socket.connect({argv[1], argv[2]});
33  return connecting_socket;
34  }();
35 
37  } catch (const exception &e) {
38  cerr << "Exception: " << e.what() << endl;
39  return EXIT_FAILURE;
40  }
41 
42  return EXIT_SUCCESS;
43 }
bidirectional_stream_copy.hh
TCPSocket::accept
TCPSocket accept()
Accept a new incoming connection.
Definition: socket.cc:151
TCPSocket
A wrapper around TCP sockets.
Definition: socket.hh:88
std::exception
std::cerr
Socket::bind
void bind(const Address &address)
Bind a socket to a specified address with bind(2), usually for listen/accept.
Definition: socket.cc:61
TCPSocket::listen
void listen(const int backlog=16)
Mark a socket as listening for incoming connections.
Definition: socket.cc:146
show_usage
void show_usage(const char *argv0)
Definition: tcp_native.cc:9
Socket::connect
void connect(const Address &address)
Connect a socket to a specified peer address with connect(2).
Definition: socket.cc:65
bidirectional_stream_copy
void bidirectional_stream_copy(Socket &socket)
Copy socket input/output to stdin/stdout until finished.
Definition: bidirectional_stream_copy.cc:12
std::strncmp
T strncmp(T... args)
std::endl
T endl(T... args)
Socket::set_reuseaddr
void set_reuseaddr()
Allow local address to be reused sooner via SO_REUSEADDR.
Definition: socket.cc:168
std
main
int main(int argc, char **argv)
Definition: tcp_native.cc:14
std::exception::what
T what(T... args)