principles

Principles in Network

Layering

Definition of layering

  • Functional components
  • Only communicate with layer directly above and below
  • Provide services to upper layer, using services provided by lower layer, and also doing its own private job

Advantages

  • Each layer can be implemented independently, as long as they keep the interfaces unchanged
  • Each layer can focus on its own job, and use lower layer’s abstracted service(For example API) easily without knowing what happens inside.
Example

layer in computer system

  • The programmers can write platform independent code.
    • If the processor changes, they only need to change the toolchain they use rather than rewrite their codes
  • If the programmers break the layering principle, for example, embed platform specific assembly code in C code when writing OS or kernel, there will be a huge cost
    • The codes are no-longer portable, they must rewrite or at least modify the codes for different processors again and again.
    • If you want to use layering, do NOT make any assumption about the lower layers
    • Try not to break the layering principle, except you really really have to do so.

Reasons for layering

  • Modularity
  • Well defined service
  • Reuse
  • Separation of concerns
  • Continuous improvement
  • Peer-to-peer communication

Encapsulation

Encapsulation is how you can pack data into packages but preserve their layering information

encapsulated package

  • Encapsulation is how layering manifest in data representation
  • Layer N data is the payload to Layer N-1
  • Example
    • HTTP data is payload for a TCP segment
    • The TCP segment is payload for IP segment
    • The IP segment is the payload for WIFI link frame

Encapsulation flexibility

Encapsulation allow you to layer recursively

For example, in a VPN

vpn package

We have

  • HTTP data inside a TCP segment
  • inside an IP segment
  • inside a TLS segment
  • inside a TCP segment
  • inside an IP segment
  • inside the link frame

Tips

  • Network protocals are ALL BIG endian

Convert between little endian and big endian in C:

1
2
3
4
5
6
7
8
9
#include <arpa/inet.h>
#include <stdio.h>
#include <stdint.h>
int main(){
uint16_t http_port = 80; //little endian, host endian
uint16_t package_http_port = htons(http_port);
printf("host:0x%04x , network:0x%04x\n" , http_port , package_http_port);
}
//host:0x0050 , network:0x5000
1
2
3
4
5
#include <arpa/inet.h>
uint32_t htonl(uint32_t hostlong); //host to network long
uint16_t htons(uint16_t hostshort); //host to network short
uint32_t ntohl(uint32_t netlong); //network to host long
uint16_t ntohs(uint16_t netshort);//network to host short