Sponge
CS144's user-space TCP library
socket_example_1.cc
Go to the documentation of this file.
1 const uint16_t portnum = ((std::random_device()()) % 50000) + 1025;
2 
3 // create a UDP socket and bind it to a local address
5 sock1.bind(Address("127.0.0.1", portnum));
6 
7 // create another UDP socket and send a datagram to the first socket without connecting
9 sock2.sendto(Address("127.0.0.1", portnum), "hi there");
10 
11 // receive sent datagram, connect the socket to the peer's address, and send a response
12 auto recvd = sock1.recv();
13 sock1.connect(recvd.source_address);
14 sock1.send("hi yourself");
15 
16 auto recvd2 = sock2.recv();
17 
18 if (recvd.payload != "hi there" || recvd2.payload != "hi yourself") {
19  throw std::runtime_error("wrong data received");
20 }
Wrapper around IPv4 addresses and DNS operations.
Definition: address.hh:13
void connect(const Address &address)
Connect a socket to a specified peer address with connect(2).
Definition: socket.cc:65
void bind(const Address &address)
Bind a socket to a specified address with bind(2), usually for listen/accept.
Definition: socket.cc:61
A wrapper around UDP sockets.
Definition: socket.hh:51
received_datagram recv(const size_t mtu=65536)
Receive a datagram and the Address of its sender.
void send(const BufferViewList &payload)
Send datagram to the socket's connected address (must call connect() first)
Definition: socket.cc:139
void sendto(const Address &destination, const BufferViewList &payload)
Send a datagram to specified Address.
Definition: socket.cc:134
const uint16_t portnum
auto recvd2
UDPSocket sock2
UDPSocket sock1
auto recvd