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 }
sock1
UDPSocket sock1
Definition: socket_example_1.cc:4
portnum
const uint16_t portnum
Definition: socket_example_1.cc:1
recvd2
auto recvd2
Definition: socket_example_1.cc:16
UDPSocket::sendto
void sendto(const Address &destination, const BufferViewList &payload)
Send a datagram to specified Address.
Definition: socket.cc:134
Address
Wrapper around IPv4 addresses and DNS operations.
Definition: address.hh:13
std::random_device
sock2
UDPSocket sock2
Definition: socket_example_1.cc:8
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
std::runtime_error
Socket::connect
void connect(const Address &address)
Connect a socket to a specified peer address with connect(2).
Definition: socket.cc:65
UDPSocket::recv
received_datagram recv(const size_t mtu=65536)
Receive a datagram and the Address of its sender.
UDPSocket
A wrapper around UDP sockets.
Definition: socket.hh:51
UDPSocket::send
void send(const BufferViewList &payload)
Send datagram to the socket's connected address (must call connect() first)
Definition: socket.cc:139
recvd
auto recvd
Definition: socket_example_1.cc:12