<jupyter_start><jupyter_text>Learning Objectives- [ ] 4.1.1 Explain the concepts of LAN, WAN, intranet and the structure of the internet.- [ ] 4.1.2 Understand the concepts of IP addressing and domain name server (DNS).- [ ] 4.1.3 Explain the need for communication protocols in a network.- [ ] 4.1.4 Explain how data is transmitted in a packet-switching network.- [ ] 4.1.5 Explain client-server architecture.- [ ] 4.1.6 Implement an iterative server with socket programming. Given the server code, students should be able to implement the client code for a given scenario, and vice-versa, e.g. for a tic-tac-toe game.  References1. <NAME>., <NAME>., & <NAME>. (2012). Cambridge international AS and A level computing coursebook. Cambridge: Cambridge University Press.2. https://www.sparknotes.com/cs/sorting/bubble/section1/:~:text=The%20total%20number%20of%20comparisons,since%20no%20swaps%20were%20made.3. https://visualgo.net/en4. https://www.youtube.com/watch?v=o9nW0uBqvEohttps://www.tutorialspoint.com/The-Transport-Layer-in-TCP-IP-Model  15.1 Types of NetworkLAN, WAN AND THE INTERNET 15.1.1 Wide Area Network (WAN)**Wide Area Network** (WAN) is a network connecting computers over a wide geographical areas, e.g within a town, region, country or even globally.The benefits of computer connected by WAN:- a 'job' could be run on a remote computer that had the required application software - a data archive that was stored on a remote computer can be accessed- a message caould be transmitted electronically to a user on a remote computer 15.1.2 Local Area Network (LAN)**Local Area Network** (LAN) is a network connecting computers on a single site, could be single room or single building.The benefits of computer connected by WAN:- the expense of installing application software on each individual PC could be saved by installing the software on an application server attached to the LAN instead- a file server could be attached to the LAN that allowed users to store larger files and also allowed files to be shared between users- Instead of suppling individual printers to be connected to a user's PC, one or more printers could be attached to a print server that was connected to the LAN; these could be higher quality printers.- Digitization of documents and emails to be stored in file servers made possible  15.2 Shape of a NetworkNetwork TopologiesIn a network, the specification on how the various devices n the network are connected are called a **topology**. The following are the different topologies:- **Bus topology**: the network contains *one shared link* to which all devices are attached.- **Mesh topology**: the network contains *direct links between devices*- **Star topology**: each end-system in the network is *linked to a central device*  15.3 The InternetThe **internet** is global communication infrastructure that links together computer and networks and is *open to public*.In contrast, **intranet** is a computer network for sharing information, collaboration tools, operational systems, and other computing services *within an organization*, usually *private*, i.e. exclude access by outsiders. Personal computers or devices are connected to LANs, which in turn connects to WANs, which then connects to the internet/intranet.**Client-server Architecture** is an architecture where a client runs an application provided by a server on a network.Example of circumstances where client-server approach is used:- the server stores a database which is accessed from the client system.- the server stores a web application which allows the client system to find or, sometimes, supply information- the server stores a web application which allows the client system to carry out an e-commerce or financial transaction**Peer-to-peer network (P2P)** is a network where each peer (networked device) can act as a client to request a file from another peer or it can act as a server when another peer requests the download of a file. Client Server Benefits- Different servers can provide for wide range of services- Provides for central storage for all files and documents- Security is centralised Drawbacks- initial set-up costs for the server and client is high- server-based netrowk requries the use of a specialist network operating system- if the server fails then the work of all users is affected. Peer-to-Peer Benefits- no dedicated server is required- additional computers can join the P2P network easily- Each computer can act as both a provider and receiver of resources Drawbacks - Decentralized system making it hard to administer- less control of identification of malware from other computers in the network.A communication **protocol** is a set of rules for data transmission which are agreed by sender and receiver so that the data is correctly transmitted. It allows devices to identify and make connections with each other, as well as formatting rules that specify how data is packaged into messages sent and received. Some other things that protocol defines:- positive voltage represents a bit with value 0- transmission speed that a sender must not exceedThe absence of this protocol could cause unwanted behaviours. For example, without a protocol, a transmitting computer, for example, could be sending its data in 16-bit segments while the receiving computer might expect the data in 8-bit segments, and thus, receiving computer will read the information wrongly.TLDR, communication protocols are needed to:- establish rules to enable communication to take place- initiate and terminate communication 5-Layer Network ModelThis network model consists of 5 layers: Layer 5. Application LayerThe functions of the application layer are:- facilitates the user to use the services of the network.- used to develop network-based applications.- provides user services like user login, naming network devices, formatting messages, and e-mails, transfer of files etc.- concerned with error handling and recovery of the message as a whole.This layer uses a number of protocols, the main among which are as follows:- **Hyper Text Transfer Protocol(HTTP)** − It is the underlying protocol for world wide web. It defines how hypermedia messages are formatted and transmitted.- **File Transfer Protocol(FTP)** − It is a client-server based protocol for transfer of files between client and server over the network. In particular, it handles the case when the end-systems have different operating systems with different file systems. - **Simple Mail Transfer Protocol(SMTP)** − It lays down the rules and semantics for sending emails. As more emails are now web-based, SMTP has largely been replaced by HTTP to access the email application.- **Post Office Protocal version 3(POP3)** and **Internet Message Access Protocol(IMAP)** are both protocols to receive emails. The distinction is the location for which the emails reside, for POP3, the emails are downloaded to the client computer whereas for IMAP, the emails aren't downloaded but kept on the server while being accessible from the client. Layer 4. Transport Layer The functions of the transport layer are:- to ensure error-free, end-to-end delivery of data from the source host to the destination host- to carry out error checking, flow control, and verification for reliable connection.This layer uses a number of protocols, the main among which are as follows:- **Transmission Control Protocol (TCP)** − It is a reliable connection-oriented protocol that transmits data from the source to the destination machine without any error. A connection is established between the peer entities prior to transmission.     - At the sending host, TCP divides an incoming byte stream into segments and assigns a separate sequence number to each segment. TCP also manages flow control so that a fast sender does not overwhelm a slow receiver.     - At the receiving host, TCP reorders the segments and sends an acknowledgment to the sender for correct receipt of segments.     - TCP has to ensure that any response is directed back to the application protocol.     E.g., World of Warcraft and Final Fantasy XIV are both MMORPGs that uses TCP mainly.- **User Datagram Protocol (UDP)** − It is a message-oriented protocol that provides a simple unreliable, connectionless, unacknowledged service. It is suitable for applications that do not require TCP’s sequencing, error control or flow control. It is used for transmitting a small amount of data where the speed of delivery is more important than the accuracy of delivery. For example, real-time connections like video streaming, VoIP, and FPS games like Overwatch and CS:GO uses UDP. Layer 3 Network LayerThe function of the network layer is to ensure correct routing over the internet. The main protocol used in this layer is Internet Protocol(IP). The protocol takes the packet received from the transport layer and adds a further header. The header contains IP addresses of both send and the receiver. To find the IP address,the DNS service to find the address corresponding to the URL supplied in the user data is likely to be used.The packet created by IP is termed **datagram** which is then to sent to the next layer, **Data Link** Layer.  Layer 2 Data Link LayerThe function of Data link layer is to convert data stream to signals bit by bit and to send that over the underlying hardware on the sendng end. At the receiving end, Data link layer picks up data from hardware which are in the form of electrical signals, assembles them in a recognizable frame format, and hands over to upper layer. Layer 1 Physical LayerPhysical layer deals with the physical connectivity of two different stations. This layer defines the hardware equipment, cabling, wiring, frequencies, pulses used to represent binary signals etc.Physical layer provides its services to Data-link layer. Data-link layer hands over frames to physical layer. Physical layer converts them to electrical pulses, which represent binary data.The binary data is then sent over the wired or wireless media. EthernetEthernet is a protocol suite designed for use in a LAN operating in the data-link and physical layer. It has the following subprotocols:- Logical Link Control (LLC) manages data transmissions and ensures the integrity of data transmissions. It has **NO** responsibility for checking if a transmission has been successfully delivered.- Medium Access control (MAC) is reponsible for assembling Ethernet packets called **frames**, in which we have the address of the transmitter and the address of the receiver. Also, it initiates frame transmission and handles recovery from transmission failure due to a collioson- Physical Coding Layer (PCS) is responsible for coding data ready for transmission or decoding data received. It either receives a frame from the MAC protocol or sends on to it.- Physical Medium Attachment (PMA) is responsible for signal transmitting and receiving. IPv4 AddressingTo define the source and destination of data in a transmission in a computer network, **IP (Internet Protocol)** addressing is used. Currently, the Internet uses IP version 4 (IPv4) addressing. It uses 32 bit (4 bytes) where a group of bits is used to defined a network (**netID**) and another group is used to define a host on the network (**hostID**). Their aim was to assign a unique, universally recognised address for each device on the internet. In the scheme, different entities are categorized into different classes (A to E). Different classes allows for different number of unique hostIDs.| Class | Class Identifier (first bits in the first byte) | Number of bits for netID | Number of bits for hostID ||-------|-------------------------------------------------|--------------------------|---------------------------|| A     | 0                                               | 7                        | 24                        || B     | 10                                              | 14                       | 16                        || C     | 110                                             | 21                       | 8                         |For example, `10101100 00010000 00000100 00101111` is an IPv4 address. Since the first 2 bits in the first octet is `10`, it means that the host resides in a class B network. To make it simpler for the user, IPv4 address are actually written in denary where the denary values for each byte is separated by dots, e.g. the IPv4 address above is displayed as `172.16.4.47`.Qn: What is the obvious limitation of the IPv4 system? Hint: Think about how many unique IDs can each class have. Classless Inter-Domain Routing (CIDR)To improve IPv4 addressing scheme, Classless Inter-Domain Routing (CIDR) is introduced. Similar to IPv4, it uses 32 bits to define a computer on the network and retains the netID and hostID functionality similar in the class system. However, it drops the rigidity of the class identifier and allows the split between the netID and the hostID to suit individual need. In this scheme, an additional 8-bit suffix is added to the address. This suffix specifiies the number of bits used for the netID. For example, consider the following IP address> `11000011000011000000011000001110/00010101`Since `00010101` is 21 in denary, this means that the first 21 bits of the address is the netID and the remaining 11 bits is the hostID. SubnettingSubnetting is the practice of dividing a network into two or more networks. It allows for a more efficient use of a hostID by applying a structure to it. For example, subnetting a medium-sized organisation's network of 150 employees. On the internet, all of the allocated IP addresses have netID pointing to the router. The router then has to interpret the hostID to direct the transmission to the appropriate hosts on one of the networks via a gateway. Network Address Translation (NAT)For end-systems to communicate over internet, there are two possible methods or approaches:- **circuit switching**. End-systems are connected to local exchanges with a switching function. These local exchanges are also connected to each other via number of intermediate nodes with a switching function.     The following steps take place for a data transfer to happen:    - the sender provides the identity of the intended receiver,    - the system checks if the receiver is ready to accept data,    - if the receiver is available, a sequence of links is established across the network. This dedicated physical, communications channel is what is termed a **circuit**    - the data is transferred,    - the links are then removed    During the duration of the communication, the whole circuit is reserved only for the two end-systems to communicate. As such it is ideal for communications which require data to be transmitted in real time.- **packet switching**. Data from the sender end-system is broken down and packaged in portions called **packets**. Packets contain header which contains instructions for delivery, which includes IP address and sequencing information, plus the data body. Thus, in this method, there is no need to maintain a circuit for the communication. The packets can travel through any path on the network to get to the destination end-system. The advantage is that the nodes can optimize the available channels to find the fastest path for the packets to go to the destination. As such, different packets might arrive at different time and they need to be reassembled based on the sequencing information that they get transmitted out with from the source. When data is transmitted, a verication check on the data when it is received is performed called the **checksum check**. Its purpose is to detect errors that may have been introduced during its transmission.In general, checksum check works as follows:- locate the byte(s) designed as the **checksum byte(s)** in the transmitted data packet- calculate the sum of the number of values of the remaining bytes in the data packet. This sum is called the **checksum value**- compare **checksum value** (in binary) with the checksum byte(s). - if the checksum value matches with the checksum byte, we conclude that that the data packet has been successfully transmitted error.  ExampleConsider the following packet of size 8 bytes. The last byte (byte 7) transmitted store the checksum.| Byte 7        | Byte 6       | Byte 5        | Byte 4        | Byte 3        | Byte 2        | Byte 1        | Byte 0        ||----------|---------|----------|----------|----------|----------|----------|----------|| `10110100` | `1000000` | `00010000` | `00000011` | `00001100` | `00000000` | `00010001` | `00000100` |Checksum value: $128+16+3+12+0+17+4=180=(10110100)_{2}$, which is equal to the checksum byte.> Qn: What is a weakness of doing checksum check?Assuming the data is transferrred in bytes using a seven-bit code, another alternative to verify the data received is **one-bit parity check**. For this check, there are two different parities that can be implemented:- **odd parity**, means that the sum of bits in each transmitted bytes is an odd number, i.e., the number 1s in a byte must be odd- similarly, **even parity** just means that the sum of bits in each transmitted bytes is an even number, i.e., the number of 1s in a byte is even.Assuming we are using *even parity* check, we have the following procedure.1. At the transmitting end, the number of 1s in the seven-bit code is counted.2. If the count gives an even number, the last bit in the byte, termed the **parity bit** is set to 0. Else, the parity bit is set to 1.3. Repeat this for every byte in the transmission,4. At the receiving end, the number of 1s in the eight-bit code is counted.5. If the count gives an even number, the byte is accepted,6. Repeat for every byte in the transmission. Note that for odd parity check, step 2 and 5 in the procedure above is adjusted accordingly.Therefore, when used, one-bit parity check can tell us which byte contains incorrect bits.> Qn: What is a weakness of doing one-bit parity check? Parity Block CheckTo overcome the weakness mentioned above, **parity block check** approach can be used. In this check, before transmission1. outgoing bytes are arranged in rectangles, where each row in the rectangle represents the bits in the byte transmitted,2. for each column in the rectangle, we will perform the one-bit parity check. The parity bits are then bundled inside a byte termed **parity byte**,3. transmit the data bytes followed by the parity byte.  ExampleConsider the following example. We have four data bytes, followed by a parity byte. The parity check used here is odd parity.|      | Bit 7 | Bit 6  | Bit 5  | Bit 4  | Bit 3  | Bit 2  | Bit 1  | Bit 0 ||-------------|---|---|---|---|---|---|---|---|| Byte 1      | 1 | 1 | 0 | 0 | 1 | 1 | 0 | 1 || Byte 2      | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 || Byte 3      | 1 | 0 | 1 | 1 | 1 | 1 | 0 | 0 || Byte 4      | 1 | 1 | 0 | 0 | 0 | 0 | 1 | 0 || Parity byte | 0 | 1 | 1 | 0 | 1 | 1 | 0 | 0 |> Qn: What information does parity byte give us? ExerciseConsider the following blocks. For each block, we have four data bytes, followed by a parity byte. The parity check used here is odd parity. Assume that there is exactly one byte that is transmitted incorrectly and that the parity bytes are correct. Identify the byte with the error. |      | Bit 7 | Bit 6  | Bit 5  | Bit 4  | Bit 3  | Bit 2  | Bit 1  | Bit 0 ||-------------|---|---|---|---|---|---|---|---|| Byte 1      | 1 | 1 | 0 | 0 | 1 | 1 | 0 | 1 || Byte 2      | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 || Byte 3      | 1 | 0 | 0 | 1 | 1 | 1 | 0 | 0 || Byte 4      | 1 | 1 | 0 | 0 | 0 | 0 | 1 | 0 || Parity byte | 0 | 1 | 1 | 0 | 1 | 1 | 0 | 0 ||      | Bit 7 | Bit 6  | Bit 5  | Bit 4  | Bit 3  | Bit 2  | Bit 1  | Bit 0 ||-------------|---|---|---|---|---|---|---|---|| Byte 1      | 1 | 1 | 0 | 0 | 1 | 1 | 0 | 1 || Byte 2      | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 || Byte 3      | 1 | 0 | 1 | 0 | 1 | 1 | 0 | 1 || Byte 4      | 1 | 1 | 0 | 0 | 0 | 0 | 1 | 0 || Parity byte | 0 | 1 | 1 | 0 | 1 | 1 | 0 | 0 | Circuit Switching Benefits- Guaranteed communication channel once established. - Bit/Bytes arrive in the correct sequential order- delay is minimized during communication Drawbacks- Dedicating one channel to a single service leaves it unavailable to other services.- it is expensive to provision an entire channel to one service and one individual routing path.  Packet Switching Benefits- Dedicated channel does not need to be setup before transmission takes place- Different routes are possible for data transfer Drawbacks - The biggest limitation of packet switching is that it is unsuitable for applications that require minimal latency. - If there is too much traffic then packets will be dropped in transit A **gateway** is a piece of networking hardware or software used in telecommunications for telecommunications networks that allows data to flow from one discrete network to another, where the networks are running different, incompatible protocol. Gateways function is to translate one protocol to another. E.g one network uses 64 bit and the other 128 bit.A **router** is a network device that forwards packets from one network to another. Based on internal **routing tables**, which stores IP addresses, routers read each incoming packet and decide how to forward it in the most efficient route.A **switch** is a hardware that connects multiple networked devices in the network. It maintains an address table containing the MAC address for each device connected to it. Switch oeprates in the data-link layer but has no access to the network layer. When a frame arrives at a switch, it is transmitted on without any routing decision (because it has already been done by the router). A **bridge** is hardware that connect two network segments. It direct packets from a node in a network segment to another node on a *different* segment. Unlike router, bridge stores MAC addresses connected to it. A **domain name** also just called a **domain** is the name of a website.A **domain name service** (DNS) is a hierarchical distributed database installed on domain name servers that is responsible for mapping a domain name to an IP address. It is to simplify to identification of IP address as the domain names are more readable than dotted decimal values. The domain names servers are connected in a hierarchy. At the top, there's powerful root servers followed by division into non-overlapping zones. Each zone has a primary name server with the database stored on it. Secondary servers get information from this primary server.Thus, naming system is hierarchical, with more than 250 top-level domains which are either generic (e.g., `.com`, `.edu` and `.gov`) or represent countries (e.g., `sg`, `id`).<jupyter_code>!ipconfig<jupyter_output>Windows IP Configuration


Wireless LAN adapter Local Area Connection* 1:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . : 

Wireless LAN adapter Local Area Connection* 2:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . : 

Wireless LAN adapter WiFi:

   Connection-specific DNS Suffix  . : 
   Link-local IPv6 Address . . . . . : fe80::81a1:3562:559a:c06e%9
   IPv4 Address. . . . . . . . . . . : 172.16.4.47
   Subnet Mask . . . . . . . . . . . : 255.255.240.0
   Default Gateway . . . . . . . . . : 172.16.0.1

Ethernet adapter Bluetooth Network Connection:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :
{'fraction_non_alphanumeric': 0.06877204913503634, 'fraction_numerical': 0.022569813405874103, 'mean_word_length': 3.5881435257410295, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 11, 'https://': 4, 'lorem ipsum': 0, 'www.': 3, 'xml': 0}, 'pii_count': 4, 'substrings_counts': 2, 'word_list_counts': {'cursed_substrings.json': 55, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '21971', 'license': 'MIT', 'n_tokens_mistral': 5938, 'n_tokens_neox': 5261, 'n_words': 3532, 'path': 'Working Folder/Fundamentals_14_Networking.ipynb', 'repo_name': 'CereboSG/Materials', 'size': '23542'}