Computer Networks
Published: 2021-05-05 15:52:53

Should be a short summary / quick cramming guide for Computer networks since i forgot everything from my networks course

only doing PART of application & network layer from TCP/IP model.

references:
https://www.homenethowto.com/ 
^ This provides a really good, *simple* concise introduction.
https://www.geeksforgeeks.org/computer-network-tutorials/#basics
https://www.geeksforgeeks.org/commonly-asked-computer-networks-interview-questions-set-1/
http://www2.ic.uff.br/~michael/kr1999/0_0-Contents.htm
Book: Computer Networking A Top-down Approach

Network: two or more devices connected through a link
link: communication pathway that transfer data from one device to another

## TOC

<u>Basics</u>
  * [Basics](#basics)
  * [protocol](#protocol)
  * [Network Topology](#network-topology)
  * [Types of area networks](#types-of-networks)
  * [Line Configuration](#line-configuration)
  * [Transmission Modes](#transmission-modes)
  * [Delay, loss, throughput](#delay-loss-throughput)

<u> Application Layer </u>
  * Relation between application layer & transport layer
network application consists of pairs of processes that send messages to each
other over a network.
  * [Socket](#socket)
  * [HTTP](#http)
  * [HTTP Persistent VS non-persistent connection & pipelining](#persistent-vs-non-persistent)
  * [Cookies to keep state](#cookies)
  * [HTTP VS HTTPS](#http-vs-https)
  * [HTTPS](#https)
  * [DNS](#dns)
  * [How DNS works](#how-dns-works)


<u> Transport Layer </u>
  * [Overview: TCP & UDP](#tcp-and-udp)
  * [Relation between transport & network layer](#transport-and-network-layer)
  * [Multiplexing & demultiplexing](#multiplexing-and-demuliplexing)
  * [UDP: Connectionless Transport](#connectionless-transport)
  * [UDP: Checksum](#udp-checksum)
  * [TCP: Connection Oriented Transport](#connection-oriented-transport)
  * [TCP Connection: 3-way handshake](#3-way-handshake)
  * [Principles for Reliable Data Transfer](#principles-for-reliable-data-transfer)
  * [TCP: Reliable Data Transfer](#reliable-data-transfer)
  * [TCP: Connection Termination](#tcp-connection-termination)
  * [TCP VS UDP](#tcp-vs-udp)

<u> Internet Layer </u>
* IP

<u> Network Layer </u>
* ethernet???
* idk other stuff????

<u> Security stuff </u>
  * [How to store passwords](#how-to-store-passwords)

<u> Putting it to practice / in summary / interview questions </u>
  * [What happens when u put URL in browser](#url-in-browser)

### <a name="basics">Basics</a>
<u>TCP/IP Model</u>
There are two models TCP / IP model (4 layers) and OSI model (7 layers). I'm lazy so I'll just go through the TCP/IP model.
![alt text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yxb4kks68peirmpxvrby.png)
![alt text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kblmv2ybr2et2h2gfzad.png)
![alt text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wj2asd4w874avqngm31d.png)
 
<small> [reference](https://www.tutorialspoint.com/OSI-vs-TCP-IP-Reference-Model)</small>
<small>[reference](https://www.guru99.com/tcp-ip-model.html)</small>
<small>[reference](https://fiberbit.com.tw/tcpip-model-vs-osi-model/)</small>


**Advantages**:
separation of responsibility / decoupled.
each layer handles different responsibility, top layer does not need tp worry about bottom layer stuff. 

<u>Host name</u>
each device in network is associate with a unique device name called hostname
<u>IP Address </u>
Internet Protocol address. 
network address of the device across the network. to identify each device in www assigns IPV4 address as unique identifier to each device on internet
IPV4 - 32 bits
IPv6 - 128 bits
<u>MAC Address </u>
Media Access Control address / physical address assigned to Network Interface Controller / Card. 

- MAC address assigned by manufacturer of hardware interface IP address assigned by network administrator / ISP
- MAC address defines device identity, IP describes how devices are connecte to internet
- MAC: broadcasting. IP: broadcasting / multicasting
- MAC: implement in data-link layer. IP: implemented in Netwrok layer
<small> [reference](https://www.guru99.com/difference-between-mac-address-and-ip-address.html) </small>

<u>Port</u>
logical channel through which data can be sent/received to an application

### <a name="protocol">Protocol</a>
> format and the order of messages exchanged between entities, & actions taken on the transmission
and/or receipt of a message or other event.

set of rules defining how entities communicate

### <a name="network-topology">Network Topology</a>
Network Topology is the arrangement with which computer systems or network devices are connected to each other.
![alt text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ui7yu0q8plq6r56gyysx.png) 
<small>See [reference](https://beginnersbook.com/2019/03/computer-network-topology-mesh-star-bus-ring-and-hybrid/)</small>

### <a name="types-of-networks">Types of Networks</a>
- LAN -- local area network. covers smallest area
- MAN -- Metropolitan are network. cover larger area than LAN smaller area then WAN
3. WAN -- Wide Area network. covers largest area. any network whose communications link cross metropolitan, regional or national boundaries. 

media for data tranmission
1. LAN: Wifi/ Ehternet cables
2. MAN: modem & wire / cable
3. WAN: leased telephone lines / satellite links

Examples
1. LAN: usually group of computer / network devices connecte together usually within same building
2. MAN: spans several buildings
3. WAN: internet

![alt text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vdqguwror0xteunb0c85.png)
 
<small>See [reference](https://community.fs.com/blog/lan-vs-man-vs-wan-whats-the-difference.html) & [examples](https://www.router-switch.com/faq/wide-area-network-examples-of-wan.html)</small>

### <a name="line-configuration">Line Configuration</a>
For communication to occur, two deivces must be connected in some way to same link at same time. There are two possible types of connections:
1. point-to-point connection
2. multipoint connection

![alt text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7aj4f26vm0daycsgyh13.png)
<small>[source](https://www.slideshare.net/dee_rosal/computer-networks-112702195) </small>

<u><b> point-to-point connection </b></u>
- dedicated link between two devices
- entire capacity is reserved for transmission between 2 devices

<u><b> multipoint / multidrop connection </b></u>
- also called "Broadcast network"
- packet transmitted by sender is received and processed by every device on link. But by address field in packet receiver determines whether the packet belongs to it or not. 
- 2 or more devices share single link
- capacity is shared spatially or temporal
1. spatial sharing - devices share link simultaneously
2. temporal sharing - users take turns using the link

### <a name="transmission-modes">Transmission Modes</a>
> transferring of data between two devices also known as communication mode

1. Simplex
2. half-duplex
3. full duplex

![alt text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/myc7dmekg662lagbs9b4.png)

<b><u>Simplex</u></b>
- communication is unidirectional
- only one of two devices on link can transmit, other can receive
- uses entire capacity of channel to send data in 1 direction

eg. keybord & monitor. keyboard only introduce input, monitor only give output

<b><u>Half-Duplex</u></b>
each station can transmit and receive but not at same time. When 1 send, other canon only receive. 
Entire capacity of channel utilized for each direction
eg. walkie talkie. must say "over" so other person can speak

<b><u>Full Duplex</u></b>
- both can transmit and receive *simultaneously*
- signals going in 1 direction share capacity of signals going in other direction
1. link contains 2 physically separate transmission paths (one for sending other receiving)
2. capacity divided between signals

e.g. landline. both can talk and hear and talk over each other lmao.

### <a name="delay-loss-throughput">Delay, Loss & Throughput</a>
This [slides](https://cs460.byu.edu/static/lectures/winter-2014/delay-loss-and-throughput.pdf) provides a really great concise overview.

###### Delay
> how long will it take for packet to travel from point A to point B

![alt text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4y849d5x1nqts3n22akk.png)
-  <b>Processing Delay</b> - time to examine packet's header and determine where to direct packet
- <b>Queuing delay</b> - packet waits to be transmitted onto link
- <b>transmission delay</b> - amount of time required to push / transmit all of packet's bits into link
eg. if Ethernet link rate is R=10Mbps & length of packet is L bits. *transmission delay is L(lenght of packet)/R (rate)*
- <b>propagation delay</b> - time required to propagate from beginning to link to router B.
*depends on physical medium of link*

<u>transmission VS propagation delay</u>
transmission: amount of time required for router to push out packet. (function of packet's length & transmission rate of link, nothing to do with distance between routers)
propagation: time taken to propagate from one router to next
(function of distance between routers, nothing to do with packet's length / transmission rate of link)

###### Packet Loss
If packet arrives to a full queue, the router will drop it since there is no place to store packet

###### Throughput
- <b>Instantaneous Throughput</b> - rate (in bits/sec) at which Host B is receiving file / packet
- <b> average throughput</b> amount of bits recevied (F) / time taken for Host B to receive all bits (T) = F/T

<u> bottleneck link </u>
for two link network, throughput is limited by the minimum throughput of both links. Otherwise known as bottleneck link
![alt text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ldebg2oqv2vj25t0jl27.png)
throughut is min{R<sub>s</sub>,R<sub>c</sub>}. min is the bottleneck link

### <a name="socket">Socket</a>
![alt text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lw8gsv91arbrsngwvgyq.png)
Interface between application layer and transport layer
eg. When process wants to send a message to another process on another host, it
shoves the message out its door (socket). Other process received message through door (socket) and acts on it. 
 
### <a name="http">HTTP</a>
> HyperText Transfer Protocol. is a **stateless** protocol

- <b> client program </b> - browser, browser implement client side of Web
- <b> server program </b> - Web server implement server side of HTTP, house Web objects each addressable by URL. 

client and server program executed on different end systems talk to each other by exchanging HTTP messages. 
![alt text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/makqolsctc7kp5rdidlp.png)

HTTP uses TCP as underlying transport protocol

1. client initiate TCP connect with server
2. Browser & server processes access TCP via socket interface 

TCP provides reliable data transfer service to HTTP, so each HTTP request response message sent by server eventually arrives intact at client. 

**layered architecture**
HTTP need not worry about lost data or the details of how TCP recovers from loss or reordering of data within the network. That is the job of TCP and the protocols in the lower layers of the protocol stack

<u> stateless </u>
HTTP server maintains no information about client. if client asks for same object, server will server it will not response saying it just served object to client. 

### <a name="persistent-vs-non-persistent">Persistent (long) VS non-persistent (short) connection</a>
> HTTP client & server will communicate for extended amount of time. must decide send each request/response over **separate (non-persistent)** OR **same (persistent)** TCP connection

<u> pipelining </u>
> requests for objects can be made back-to-back without waiting for replies to pending requests

default HTTP mode uses HTTP with pipelining & connection closes when not used for certain time

<u> persistent VS non-persistent </u>
- brand new connection established and maintained for each requested object. TCP buffers allocated TCP variable allocated in both server & client --> burden
- each object suffer delivery delay of 2 RTT - 1 RTT to establish TCP connected 1 RTT to request & receive object. 

![alt text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/72l2qurb5p3el9rhma10.png) 
<small>[reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Connection_management_in_HTTP_1.x?retiredLocale=ar)</small>


### <a name="cookies">Cookies</a>
Website needs to identify users & serve content as function of user identity.

![alt text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5lu33fak4kcoi8vlthnn.png)

### <a name="http-vs-https">HTTP VS HTTPS</a>
![alt text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uhx4hp31uy0lyrz02dj6.png)
- HTTPS (or rather SSL) is a transport layer protocol, HTTP is a application layer protocol
- HTTP transfer data in plain text HTTPS transfer data encrypted. hacker can read sensitive data or modify data, entities communicating will be none the wiser
- HTTPS is slower since it consumes computation power to encrypt communication channel
- independent authority (certificate authority, CA) verifies identity of certificate owner. over HTTPS, one cannot impersonate. 
- HTTPS **can't stop stealing confidential information from pages cached in browser**

<small>[reference](https://www.guru99.com/difference-http-vs-https.html)</small>


### <a name="https">HTTPS</a>
Details in this section taken from [cloudflare](https://www.cloudflare.com/learning/ssl/what-happens-in-a-tls-handshake/)
> TLS is an encryption protocol designed to secure Internet communication. During TLS both parties exchange messages to acknolwedge eahc other, verify each toehr & establish encryption algos & agree on session keys
TLS handshakes are a foundational part of how HTTPS work.
 

<u> Process </u>
- Client Hello
  - client initiates by senidng "hello" along with:
  - TLS version client supports
  - ciper suite supported &
  - client random (string of random bytes)
- Server Hello
  - Server's SSL cert
  - Server's chosen cipher suite
  - server random
- Authenticaion
  - client verfies server SSL cert with cert authority (CA)
- premaster secret
  - client sends *premaster key* (random string of bytes)
  - premaster key is encrypted with server public key (can only be seen by server)
- Session keys created
  - BOTH client & server generate session keys from
  - client random
  - server random
  - premaster key
- Client ready
  - client sends "finished" encrypted with session key
- Server ready
  - server send "finished" encrypted with session key

![alt text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/806jmiwcducnbzyv2c95.png)
![alt text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g761ua8prtv55zzxfxgc.png)
![alt text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ejentpinfvgvz7l9lztw.png)
  

General phases
- Negotiation
  - server & client agree on cipher suite 
  - server sends SSL cert
- Authentication
  - client check that server cert is authentic / can be trusted
- Key Exchange
  - server & client create session key (symmetric keys)
  
 
<u> Trusting certificates </u>
- CA
  - certificate is issued by a Certificate Authority that browser trusts (usually pre-installed on browser, can add & remove)
- Digital Signature
  - verify that person presenting cert is also person controlling the domain
  - certificate is "signed" by another authority to declare person controlling cert controls domain
  - Authority uses "private key" (basically a unique key only authority can produce, much like a signature) to encrypt contents of cert. cipher text is attached to cert as digital signature
  - anyone can use public key to decrypt and match contents. only authority can produce the signature. 
   - browser can use CA public key to check if signature is valid. 


man in middle can technically replay info from client to server. but information is encrypted and attacker will not have server's private key to decrypt and read information. 

![alt text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pmli43mw98b8d6ec2zp4.png)

Further reading:
https://robertheaton.com/2014/03/27/how-does-https-actually-work/
https://medium.com/@vanrijn/an-overview-of-the-ssl-handshake-3885c37c3e0f
https://www.thesslstore.com/blog/explaining-ssl-handshake/

### <a name="transmission-media">Transmission Media</a>
physical path between transmitter and receiver (i.e. channel through which data is sent from one palce to another) 

### <a name="dns">DNS</a>
> Domain Name system. translates hostname (human friendly names) to IP addresses.

- **distributed database** implemented in hierarchy of **DNS servers**
- application-layer protocol that allows hosts to query distributed database. 

when browser extracts hostname, DNS client sends query for hostname to DNS server. DNS server will reply with IP address.

DNS adds delay but delay is circumvented as **IP address usually cached in "nearby" DNS server**

### <a name="how-dns-works">How DNS works</a>
> DNS reply & query sent in UDP datagrams to port 53. DNS is a distributed hierarchical Database

<u> Overview </u>
1. browser invoke client side of DNS with hostname to be translated
2. DNS sends query message to network. *All DNS reply & query are sent within UDP datagrams to port 53* 
4. DNS in user host receive DNS reply message with desired mapping
5. mapping passed to invoking application (browser) 

<u> distributed hierarchical Database </u>
> DNS uses a large number of servers,
organized in a hierarchical fashion and distributed around the world. mappings
are distributed across the DNS servers

- root DNS server (at top) 
- top level domain (TLD) DNS server
- authoritative DNS server (at bottom) 
![alt text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lt2405c4ht43vh3mtxri.png)
e.g. `amazon.com` -> client contact root server --> root server return IP address for TLD server (the com DNS server) -> client contact TLD server -> TLD server returns IP addrss for authoritative server for `amazon.com` -> authoritative server returns IP address

- Local DNS server
not in hierachy. Each ISP will have local DNS server, when host connect to ISP, ISP provides host with IP address of DNS server (typically via DHCP) 
host makes DNS query, query sent to local DNS server which acts as proxy forwarding query to DNS server hierarchy.
DNS queries can be iterative or recursive
![alt text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5b4lidux9arananbq6l5.png) 
![alt text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/huqrkx55i35svgko1laf.png)

<u> Caching </u>
in query chain, DNS servers do caching so results can be returned more quickly 
 
### <a name="tcp-and-udp">Overview: TCP & UDP</a>
TCP/IP network makes 2 distinct transport-layer protocols to application layer:
- **TCP** (Transmission Control Protocol)   
  - provides reliable, connection-oriented service to the invoking application

- **UDP** (User Datagram Protocol) 
  - provides unreliable connection-less service to invoking application

### <a name="transport-and-network-layer">Relation between transport & network layer</a>
extend host-to-host delivery service provided by network layer to process-to-process delivery service for applications running on hosts.

> At destination host, transport layer receives segments from network layer below, transport layer responsible for delivering data in segments to appropriate application process running in host. 

eg. in your computer u run 4 processes (FTP session, webpage HTTP session + 2 telnet sessions) transport layer on receiving data from network layer must direct it to 1 of these 4 processes

![alt text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ovr6pldcm66fkesfa014.png)
Process can have 1 or more sockets (door through which data passes from network to process) transport layer in receiving host delivers data to an intermediary socket. 

Example.
transport layer: TCP / UDP
network layer: IP 
 
### <a name="multiplexing-and-demuliplexing">Multiplexing & demultiplexing</a>

> **demultiplexing**: at receiving end, transport layer examine segment fields to identify receiving socket & deliver it to correct socket 
**multiplexing**: at source host, gather data chunks from different socket, encapsulate each data chunk with header info to create segment and pass them to network

![alt text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1aye1h4yzk8d2oy6rq2t.png)
<small>[reference](https://www.geeksforgeeks.org/multiplexing-and-demultiplexing-in-transport-layer/)</small>

TCP and UDP perform demultiplexing & multiplexing by including 2 fiels in segment headers:
- **source port**
- **destination port**

![alt text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f3c6r2vw8lziz0ewo249.png)
port numbers are 16 bit
both fields *together* uniquely identity application process running on destination host

Each socket assigned port umber when segment arrives at host tarnsport layer examines destination port number and directs segment to corresponding socket. Segment's data passes through socket to attached process.


Refernce:
http://www2.ic.uff.br/~michael/kr1999/3-transport/3_02-fund.html


### <a name="connectionless-transport">UDP: connectionless tarnsport</a>
> *connectionless* because there is no handshaking between sending & receiving transport-layer entities before sending segment.

1. takes messages from application process
2. attaches source and destination port number (for multiplexing & demultiplexing)
3. adds 2 other small fields
4. pass resulting segment to network layer
5. network layer encapsulate transport-layer segment into an IP datagram & make best-effort attempt to deliver segment to receiving host
6. If segment arrives at receiving host, UDP use destination port number to deliver segment data to correct application process.  

<u>In Practice</u>
DNS is an applicatio-layer protocol that uses UDP
when DNS application in host wants to make query

1. application constructs DNS query message & passes it to UDP
2. host-side UDP adds header fiels to message
3. host-side UDP passes resulting segment to network layer
4. netowrk layer encapsulates UDP segment to datagram & sends datagram to name server
5. DNS application at querying host waits for reply to query
6. If no reply (becuase underlying network lost query / reply), it tries sending query to another name server / inform invoking application that it can;t get reply 


<u> Why UDP </u>
- **Lesser delays**: No handshake = no delay to establish connection
- **Small packer header overhead**
- **Support more clients**: No connection state  = server devoted to particular application can support more active client when application runs over UDP rather than TCP

### <a name="udp-checksum">UDP: Checksum</a>
> provides error detection: ensure bits in UDP segment have not been altered 

![alt text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zi2pbj0wnwjm7kqzom99.png)
- Sender
  - sender performs 1s complement of sum of all words in segment (any overflow is wrapped around) 
  - result is put in checksum field
- Receiver
  - if segment arrives
  - all 4 16-bit words are added together with cehcksum
  - sum = 1111111111111111
  - segment has no errors. If there is >=one 0 there are errors.

<u> Why checksum? </u>-layer protocols) between source & destination provide error checking. 


### <a name="connection-oriented-transport">TCP: Connection-Oriented Transport</a>
> TCP(*Transmission Control Protocol*)Internet's transport-layer connection-oriented reliable transport protocol
TCP connection provides a **full-duplex service**.
TCP connection is always **point-to-point** (between single sender & single receiver)

<b><u>Connection-Oriented</u></b>
before 1 application process sends data to another, 2 processes must first "handshake" with each other

<b><u>Reliable Data Transfer</u></b>
TCP relies on principles of reliable data transmission
- error detection
- retransmission
- cumulative acknowledgement
- timers 
- header fields for sequence & acknowledgement numbers

### <a name="3-way-handshake">TCP Connection: 3 way handshake</a>
> **3-way handshake** process to establish a fully-duplex communication

![alt text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ctrzrrv9heu6anmvn8jv.png)

- **SYN**
  - client wants to establish connection with server.
  - client send segment with SYN (synchronize Sequence Number) that informs server that client is likely to start communication with with what sequence number it starts segment with
- **SYN+ACK**
  - server responds to client request with SYN + ACK signal bits set.
  - ACK: signifies response of segment it received
  - SYN: signifies with what sequence number it is likely to start segments with
- **ACK**
  - client acknowledges response of server & both establish reliable connection with which they will start the actual data transfer

![alt text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dts9h1v77j1met2iei1e.png)
 

SYN & SYN+ACK establish connection parameter (sequence number) for one direction & it is acknowledged
SYN+ACK & ACK establish the connection parameter (sequence number) for other direction & it is acknowledged. 

![alt text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/azl3l29n2u1rpfsoaxkk.png)
 
![alt text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4fzoeuo49e3pns5fxmvn.png)
 
![alt text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m8jthtwvzbgavshnzlff.png) 
- [educative](https://www.educative.io/courses/grokking-computer-networking/xlMyzABwL33)

### <a name="principles-for-reliable-data-transfer">Reliable Data Transfer - Concepts + Introduction</a>
Information in this section is all taken from this [medium article](https://zackofwest.medium.com/reliable-data-transfer-protocols-rdt-the-reliability-guarantee-that-keeps-the-internet-running-e555a4fb375d) by Zack West.
I **HIGHLY RECOMMEND* reading it. It introduces concepts for reliable data transfer in a really simple and concise way. In summary.

Reliable data transfer has 2 key components:
1. data loss
2. data corruption

There are a few components that address this:
- ACK
  - acknowledgement from receiver to let sender know data is received.
- Timeout
  - timeout in case sender never receives ACK/NACK response

<u> Mapping ACK/NACK to data segment sent </u>
- stop and wait
  - sender sends single data segment and waits for response
- SEQ (send multiple data segments)
  - SEQ (sequence numbers). When sender sends multiple data segments. SEQ lets the sender know which ACK / NACK message is for which data segment

<u> Pipelined protocols </u>
- Go back N
  - sliding window
  - sender transmit packets waits on ACKs from receiver.
  - as sender receives ACKs base value (representing window minimum) slides forward "quthorixing" incremented SEQ numbered-segments
  - receiver: packets received out of order are discarded
- selective repeat
  - receiver can accept packets out of order.
  - receiver can accept & buffer frames following a damaged or lost one
  - retransmission of packets happen when:
    - implicit: packets are not ACKed nefore time out
    - explicit: explicit NACK

![alt text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/42s3labtk57baedmeodg.png)
![alt text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/acu73rd4o8d4vgz43z79.png)
 
 
GBN & SR further reading:
- https://www.geeksforgeeks.org/sliding-window-protocol-set-3-selective-repeat/
- https://www.studytonight.com/post/flow-control-gobackn-arq-protocol
- https://www.studytonight.com/post/flow-control-selective-repeat-protocol

TCP Is a mix of GBN & SR (https://networkengineering.stackexchange.com/a/29478)


### <a name="reliable-data-transfer">TCP Connection: Reliable Data Transfer</a>
> TCP creates **reliable data transfer** service on top of IP's unreliable best-effort service.
TCP reliable data transfer service ensures data stream that a process reads out of its TCP receive buffer is uncorrupted 

- data received from application
  - TCP receive data, encapsulate data in segment, pass segment to IP (each segment includes a sequence number - byte-stream number of first data byte in segment)
- timer timeout
  - TCP re transmits segment that caused timeout
  - TCP restarts timer
- ACK receipt
  - sener TCP determine whether ACK is *first time ACK* for segment sender has yet to receive or a *duplicate ACK*
  - first-time ACK: sender knows all data up to byte being acknowledge has been received correctly. It can update its TCP state variable.
![alt text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nrae7r59otykx9n7kae1.png)
ACK from Host B to Host A is lost. Host A re transmits segment after timeout. Host B receives the retransmission and observers from sequence number that the segment contains data that has already be received. Host B will discard bytes in retransmitted segment. 
 ![alt text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gfzfq68hsu21alpb5oca.png)
if second ACK segment arrives before the new timeout ends, the second segment (seq=100 sender segment) will not be sent.
 ![alt text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6g0ztfuj9ccmz326zfvc.png)
 ![alt text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6beptavczoe84n19d75l.png)
Host A sends 2 segments but ACK of first is lost.
Host A gets ACK of 120. so it knows B has received both segments.
Host A will not resend second segment. 
 


### <a name="tcp-connection-termination">TCP Connection Termination</a>
4 step process
![alt text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/su58a2aae3xwnnxr52jq.png)

### <a name="tcp-vs-udp">TCP VS UDP</a>
Information from this sectio is taken from [Guru99](https://www.guru99.com/tcp-vs-udp-understanding-the-difference.html)

- TCP
  - use when both client & server independently send packets at same time & occasional delay is acceptable (eg. Online Poker)
- UDP
  - both client and server may separately send packets & occasional delay is not acceptable (multiplayer games)
  - multimedia

Applications / Advantages
- TCP 
  - establish connection between 2 computers
- UDP  
  - can be use for servers that answer small queries from larger client base (eg.DNS)
  - used by time-sensitive applications 
  - multicasting sending

![alt text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rzx1m8a3zw16kh5no6zi.png)
 

### <a name="url-in-browser">What happens when u put URL in browser</a>
I **HIGHLY RECOMMEND** this [medium article](https://medium.com/@maneesha.wijesinghe1/what-happens-when-you-type-an-url-in-the-browser-and-press-enter-bb0aa2449c1a) by maneesha wijesinghe1

It is super detailed and if you are short on time, the headers provide a really good brief.
basically,
1. type in URL
2. cache check for DNS record with IP address of URL. browser cache, OS cache, router cache, ISP cache
2. not in cache, ISP DNS server do DNS lookup of URL (to get IP address)
3. browser initiate TCP connection with server (of the website). SYN/ACK stuff
4. TCP connection initiated, browser send HTTP request to server
5. server contains web server (apache, nginx) server handles request sends back resposne
6. server send HTTP response (usually for SPA, the page loads coz browsers sends HTTP GET and webserver returns index.html)
7. browser displays HTML content

### <a name="how-to-store-passwords">Store password in DB</a>
https://www.vaadata.com/blog/how-to-securely-store-passwords-in-database/
https://www.geeksforgeeks.org/store-password-database/
https://auth0.com/blog/adding-salt-to-hashing-a-better-way-to-store-passwords/
1. Dont store plain text
2. Hash passwords
3. Add salt (random phrase) to password
4. Add dynamic salt (random phrase that changes for every user). each user will have to store hashed password + dynamic salt.
5. use BCrypt VS md5. (BCrypt does salt)

Note:
- never tell someone their selected password is not unique

<u>md5</u>
very quick hashing function -> faster calculation - faster brute force attacks

<u>BCrypt</u>
[more info](https://javascript.plainenglish.io/how-bcryptjs-works-90ef4cb85bf4)
1. generate salt
2. hash password with generated salt
3. can choose value of salt Rounds (increase time to compute hash & reduce brute force attacks) 
however time to compute hash must not be too long so users will not run out of patience

<u>bcrypt VS md5</u>
- slower => brute force attacks are less effective
- can increase the number of iterations to match computing power. (if computing power increases)[info](https://javascript.plainenglish.io/how-bcryptjs-works-90ef4cb85bf4)
[Auth0](https://auth0.com/blog/hashing-in-action-understanding-bcrypt/) article explains why bcrypt (salt generation) is preferred