*General, messy cheatsheat & almalgamation of notes*:
*General Protocol Overview*:
- UDP - [User Datagram Protocol](app://obsidian.md/User%20Datagram%20Protocol)
- TCP - Transmission Control Protocol
- IP - Internet Protocl
- ICMP - Internet Control Message Protocol
- ARP - Adress Resolution Protocol
- [HTTP](app://obsidian.md/Hypertext%20Transfer%20Protocol) - [Hypertext Transfer Protocol](app://obsidian.md/Hypertext%20Transfer%20Protocol)
- [DNS](app://obsidian.md/Domain%20Name%20Server) - [Domain Name Server](app://obsidian.md/Domain%20Name%20Server)
The first telegraphs were typically optical, and then came the *electromagnetic telegraph*.
*IMP*: Early form of 'router', used as a translation for a company's computer and ARPANET
ARPANET: The first small 'internet', was packet switched. Limitations however were 5
*ARP*: Address Resolution Protocol, maps [[Mac Address|MAC]] to IP and IP to MAC. ARP requests are used to ask 'who is X' and temporarily store that information.
*Switch*: Connects multiple nodes in a network together, smarter than a HUB. A switch knows the mac addresses of the hosts connected to it.
*Router*:
- Connects 2 networks
- Allows them to connect to each other
- Decides where traffic should go
*Gateway*:
- Connects two *different kinds* of networks together
- Most routers are gateways, not all gateways are routers
*Default Gateway*:
- The adress on the local subnet that nodes will send to if the network address is *outside* the subnet.
- The border between the local network and the outer internet
*Local Network*: A bunch of computers connected to each other via the same medium,
- Can have its own addressing scheme that is *locally* unique
Ethernet Local Adressing:
- Each node has a locally unique identifier,
- [[Mac Address|MAC]] addresses that are 48 bits long, the first 24 bits are assigned to manufacturers, and the second half is a 'unique' value set by manufacturers
[[Simple Traversal of UDP through NAT]]:
- Known 3rd party proxy
- Players connect to proxy
- Proxy tells players about each other
- Players communicate through this proxy
*Internet Protocol*:
- IPv4
- Part of the 'network' layer
- Used for routing packets across *different* networks
[[Hypertext Transfer Protocol|HTTP]]:
- Originally documents contain links to other documents
- Universal Resource Locators, Content Types, not just text
- Instead of docs we can now serve applications
HTTP Verbs:
- GET, POST, PUT, DELETE (HEAD, TRACE, OPTIONS, PATCH <- less interested in these)
[[REST]]:
- Representational State Transfer
- Because HTTP is stateless, but state is useful
HTTP Response Codes:
- 100 - Informational
- 200 - Sucess
- 300 - Redirection
- 400 - Bad request
- 500 - Server fault
DNS:
- Cache results agressively (values have a 'lifetime')
- Recursive structure
Before DNS:
- HOST file, distributed by hand
- Outgrew this early
- Local HOSTS file is still useful for development and testing
#### TCP vs UDP
TCP Solutions:
- Reliable
- Automatic Splitting
- Streams
- Throttling
- If overloading, send fewer packet at a time
- Throughput available ([Little's Law](app://obsidian.md/Little's%20Law))
Sequence of calls to make a TCP connecion
Compares to UDP:
- TCP came first
- One size fits all
- UDP is easier to work with & we can build things on top of that, tCP can be heavy wait
- Low overhead
- Stateless, no connections to main intrinsically
#### NAT
NAT Types:
- Strict/[Symmetric](app://obsidian.md/Symmetric%20Matrix)
- Most restrictive
- breaks [Simple Traversal of UDP through NAT](app://obsidian.md/Simple%20Traversal%20of%20UDP%20through%20NAT) but has the best security
- Open / Full [Cartesion Plane](app://obsidian.md/Cartesion%20Plane)
- Least restrictive, easiest for game devs
- Hole through firewall
- Moderate / Port Restricted
### IPv4
![[IPv4 Address|IPv4]]
### [[IPv6]]
![[IPv6]]
### Circuit-Switching
![[Circuit-Switching]]
### Packet Switching
![[Packet-Switching]]
### OSI
![[OSI Stack]]
### TCP
![[TCP-IP Model]]
### URL
![[URL]]
### Little's Law
![[Little's Law]]
Through is messages over time
We can because we can alter occupancy to try getting better throughput, one way measurement.
Bandwith is the maximum data transfer rate of a network (theoretically possible)
- Round Trip Time - ms
- Jitter - $\Delta \text{Latency}$
# Winsock API Documentation
### closesocket
Closes a socket;
#### Signature
`closesocket(SOCKET socket)`
#### Parameters
- socket: Socket to close
#### Return Value
0 of the socket was closed sucessfully, SOCK_ERROR if not.
#### Example
```c++
int result = closesocket(socket_handle);
if (result == SOCKET_ERROR) {
sockerror("Failed to close socket");
return EXIT_FAILURE;
}
```
---
### htons
Converts a ushort from host endian to big endian
#### Signature
`unsigned short htons(unsigned v)`
#### Parameters
- v: 16 bits to convert
#### Return Value
- Big ended version
#### Example
```c++
addr.sin_port = htons(8080);
```
---
### recvfrom
#### Signature
`int recvfrom(SOCKET socket, char* buf, int len, int flags, sockaddr* from, int fromlen)`
#### Parameters
- socket: Socket to receive from
- buf: Pointer to buffer to fill with data
- len: Length of the buffer
- flags: Special flags fro recv
- from: optional pointer to store the receiving's address
- fromlen: size in bytes of the address 'from'
#### Return Value
0 if disconnected, <0 if error, >0 will be the number of bytes received.
#### Example
```c++
char receive_buffer[256]{};
size_t bytes_received = recvfrom(
socket_handle,
&receive_buffer[0],
sizeof(receive_buffer),
0,
nullptr,
nullptr
);
if (result < 0) {
sockerror("Failed to receive data");
closesocket(socket_handle);
WSACleanup();
return EXIT_FAILURE;
}
```
---
### sendto
#### Signature
`int sendto(SOCKET socket, const char* buf, int len, int flags)`
#### Paramterse
- socket: Socket to send from
- buf: Pointer to data to send
- len: Amount in bytes of data to send
- flags: Special flags for sending
#### Return Value
Returns 0 on sucesss, SOCK_ERROR if failure.
#### Example
```c++
int result = sendto(
socket_handle,
payload.data(),
static_cast<int>(payload.size()),
0,
reinterpret_cast<const SOCKADDR*>(&addr),
sizeof(sockaddr_in)
);
if (result == SOCKET_ERROR) {
sockerror("Failed to send data");
closesocket(socket_handle);
WSACleanup();
return EXIT_FAILURE;
}
```
---
### socket
#### Signature
`SOCKET socket(int af, int type, int protocol)`
#### Parameters
- af: The address family specification (AF_INET for internet)
- type: Type specification for socket (ex. SOCK_DGRAM)
- protocol: What internet protocol to use (UDP/TCP)
#### Return Value
Returns the created socket on sucess, SOCKET_ERROR if failed to create.
#### Example
```c++
const SOCKET socket_handle{socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)};
if (socket_handle == INVALID_SOCKET) {
sockerror("Failed to create socket");
return EXIT_FAILURE;
}
```
---
### WSACleanup
#### Signature
`int WSACleanup()`
#### Return Value
0 if succesfull, SOCKET_ERROR if failure.
#### Example
```c++
const int result = WSACleanup();
if (result == SOCKET_ERROR) {
sockerror("Failed to cleanup");
}
```
---
### WSAGetLastError
#### Signature
`int WSAGetLastError()`
#### Return Value
Returns an error code produced by the last socket-related function,
this will return 0 of there was no error to note.
#### Example
```c++
printf("Error Code: %d\n", WSAGetLastError());
```
---
### WSAStartup
#### Signature
`int WSAStartup(WORD wVersionRequired, LPWSADATA lpWSAData)`
#### Arguments
- wVersionRequired: Version of the sicksock API to use, typically just `MAKEWORD(2,2)`
- lpWSAData: Pointer to WSAData to receive implementation details
#### Return Value
Returns 0 if sucess, else returns an error code.
#### Example
```c++
if (WSAStartup(MAKEWORD(2, 2), &wsa_data) != NO_ERROR) {
sockerror("Failed WSAStartup");
return EXIT_FAILURE;
}
```
### accept
This function permits some attempted (incoming) connection on the ggiven socket
#### Signature
`SOCKET accept(SOCKET sock, sockaddr* addr, int *addrlen)`
#### Parameters
- sock: Listening socket descriptor
- addr: (Optional out-parameter) pointer to a buffer to store the receiver's address
- addrlen: (Optional out-parameter) pointer to an `int` that contains the length of the structure behind the pointer
given to addr
(if given)
#### Return Value
Returns a new SOCKET descriptor for the new socket, INVALID_SOCKET if failed.
#### Example
```c++
sock_addr addr;
int length = sizeof(sock_addr);
SOCKET sock = accept(listener_socket, &sock_addr, &length);
if (sock == INVALID_SOCKET) {
eprintf("Failed with code %d\n", WSAGetLastError());
}
```
---
### bind
Associates some local address with the given socket
#### Signature
`int bind(SOCKET socket, const sockaddr* addr, int length)`
#### Parameters
- socket: Socket descriptor for the unbounded socket
- addr: Pointer to a sockaddr variable to assign to this socket
#### Return Value
0 if no error, SOCKET_ERROR if it failed for some reason.
#### Example
```c++
// setup address ex. with htons and & inet_pton
if (bind(socket, (const sockaddr*)&address, sizeof(address)) == SOCKET_ERRO) {
sockerror("Failed to bind socket");
return EXIT_FAILURE;
}
```
---
### connect
Establish a connection to the specified socket.
#### Signature
`int connect(SOCKET socket, const sockaddr* addr, int length)`
#### Parameters
- socket: Socket handle to connect to
- addr: Pointer to sockaddr structure
- length: Length of data at 'addr'
#### Return Value
If no error, returns 0, else it returns SOCKET_ERROR.
#### Example
```c++
// setup address ex. with htons and & inet_pton
if (connect(socket, (const sockaddr*)&address, sizeof(address)) == SOCKET_ERRO) {
sockerror("Failed to establish connect");
return EXIT_FAILURE;
}
```
---
### listen
Sets a socket handle to be in listening mode for a any new incoming connection.
#### Signature
`int listen(SOCKET socket, int backlog)`
#### Parameters
- socket: Socket descriptor to set to listen mode
- backlog: Maximum length for the queue of pending connections
#### Return Value
#### Example
```c++
if (listen(socket, SOMAXCONN)) {
sockerror("Failed to put into listen mode");
return EXIT_FAILURE;
}
```
---
### recv
Receives data from a *connected* socket *OR* a unconnected socket that was bound (`bind`).
#### Signature
`int recv(SOCKET socket, char* buffer, int length, int flags)`
#### Parameters
- socket: Socket to receive
- buffer: Pointer to buffer to store incoming data
- length: Max number of bytes to write to 'buffer'
- flags: Bitflags for specific options, (MSG_PEEK for peeking data, MSG_OOB for OOB data, and MSG_WAITALL (see official
documentation for full details))
#### Return Value
Returns 0 if no bytes received, a int above 0 for the number of bytes received, and a value below zero to indicate
an error happened.
#### Example
```c++
char receive_buffer[256]{};
int bytes_received = recv(socket_handle, &receive_buffer[0], sizeof(receive_buffer), 0);
if (result < 0) {
sockerror("Failed to receive data");
closesocket(socket_handle);
WSACleanup();
return EXIT_FAILURE;
}
```
---
### send
Send data through a connected socket.
#### Signature
`int send(SOCKET socket, const char* buffer, int length, flags)`
#### Parameters
- socket: Socket to send through
- buffer: Pointer to beginning of payload
- length: Length of payload in bytes
- flags: Bitflags for specific options on protocols to use
#### Return Value
0 if no error, SOCKET_ERROR if there was any issue.
#### Example
```c++
std::string message = "Hello World";
int result = send(socket, message.c_str(), (int)message.length(), 0);
if (result != 0) {
sockerror("Failed to send data");
closesocket(socket_handle);
WSACleanup();
return EXIT_FAILURE;
}
```
---
### shutdown
Disables the sending and/or receiving function of a given socket.
#### Signature
`int shutdown(SOCKET socket, int which)`
#### Parameters
- socket: Socket to shutdown functionality
- how: Flag to describe which to disbale, (SD_RECEIVE for recieving, SD_SEND for sending, SD_BOTH for both)
#### Return Value
Returns 0 if success, SOCKET_ERROR if failure.
#### Example
```c++
if (shutdown(socket, SD_RECEIVE) != 0) {
sockerror("Failed to stop listening");
closesocket(socket_handle);
WSACleanup();
return EXIT_FAILURE;
}
```