First understanding of network programming


Network programming is a means of data exchange between programs running on different computers connected to a network.

  • Network related hardware devices:

    • Network Card Router Switch Data Transmission (Media) Optical Fiber (Optical Cable) Digital Signal Analog Signal Demodulator Repeater Hub Network Cable
  • Network-related agreements (predetermined procedures and rules)

    • HTTP Hypertext Transfer Protocol HTTPS
    • FTP file transfer protocol
    • TCP: Transmission Control Protocol
    • UDP: User Datagram Protocol
    • IP: Internet Internet Protocol
    • ARP/RARP Address Resolution Protocol Reverse Address Resolution Protocol
  • IP address: ipv4 consists of 4 integers within 255

    • An IP address in a network, unique, uniquely identifies a device in the network

    • IP addresses are like mobile phone numbers

  • Subnet mask: IP address & subnet mask == network address

    • IP address & (~subnet mask) == local IP address

basic concept


seven-layer model

  • theory
  • The International Organization for Standardization (ISO for short) is an international non-governmental organization in the field of standardization.
  • Open System Interconnection Reference Model (OSI), or OSI model for short, is a conceptual model proposed by the International Organization for Standardization and an attempt to make computers interconnect the standard framework for networking worldwide.
  • Divide the network into seven layers
|  application layer            |  Application        |
|  presentation layer            |  Presentation       |
|  session layer            |  Session            |
|  transport layer            |  Transport          |
|  Network layer            |  Network            |
|  data link layer       |  Data Link          |
|  physical layer            |  Physical           |
  • Physical layer: (not referring to the physical device that transmits data, not fiber, not network cable)
    • It mainly defines the physical equipment standards, such as the interface type of the network, the interface type of the optical fiber, the transmission rate of various transmission media, etc.
    • The main function is to transmit bit stream (the strength of 0/1 current indicates digital-to-analog conversion and analog-to-digital conversion)
    • Physical layer data: bits
    • Physical setup: Repeater Hub
  • data link layer:
    • Defines how formatted data is transmitted in frames and how to control access to physical media
    • Serial port experiment 115200
    • Usually provides error detection and correction Parity CRC
    • Data Link Layer Data: Frames
    • Physical setup: bridges, switches
  • Network layer:
    • Provides connectivity and routing between two host systems in a network at different address locations.
    • Network layer physical device: router
  • Transport layer:
    • It is mainly to segment and transmit the data received from the lower layer, and then reorganize after reaching the destination address.
    • Data transport layer: data segment
  • Session layer:
    • Responsible for establishing, managing, and terminating sessions between presentation layer entities
  • Presentation layer:
    • Provide encoding and conversion for application layer data, data compression and decompression, encryption and decryption, data conversion, etc.
  • Application layer:
    • Provide application interface for computer users and provide users with various network services
    • Device: Gateway

TCP/IP Network Model

  • practice

  • The network is divided into four layers

    ISO/OSI Seven-layer network model                       TCP/IP Four-layer network model
|  application layer            |  Application        |                 |   HTTP      |
+-------------------+---------------------+                 |   FTP       |
|  presentation layer            |  Presentation       |     application layer       |   SMTP      |
+-------------------+---------------------+                 |   HTTPS     |
|  session layer            |  Session            |                 |   TELNET    |
|  transport layer            |  Transport          |     transport layer       |  TCP  UDP   |
|  Network layer            |  Network            |     Network layer       | IP  ICMP  IGMP  ARP  ARAP |
|  data link layer        |  Data Link          |                 |             |
+-------------------+---------------------+ Network Interface (Link) Layer |PPP  PPPOE   |
|  physical layer            |  Physical           |                 |             |           

IP address

  • IP address (Internet Protocol Address) refers to the Internet Protocol address, also translated as Internet Protocol Address

  • The IP address is a unified address format provided by the IP protocol. It assigns a logical address to each network and each host on the Internet, thereby shielding the difference in physical addresses.

  • IPv4 4 bytes 32 binary bits theoretically 2^32 (4.3 billion) IP addresses

    • 4 bytes 32 binary bits
    • Representation
      • Dotted decimal is separated by 4 integers from 0 to 255.
      • Integer hexadecimal 0xC0A858E9 High-order left and right low-order right
    • IPv4 address classification
      • Class A: 0+7-bit network address + 24-bit local address 0000 0000 – 0111 1111 128 1.x.x.x
      • Class B: 10+14-bit network address + 16-bit local address
      • Class C: 110 + 21-bit network address + 8-bit local address
      • Class D: 1110 + 28-bit multicast address
      • Class E: 11110 + switch for future experiments
    categoryMaximum number of networks
    number of network addresses
    IP address rangeMaximum number of hosts in a single network segmentPrivate IP address range
  • IPv6 claims to be able to assign an IP address to every grain of sand on earth 16 bytes 128 binary bits

    • display method
      • Colon hex X:X:X:X:X:X:X:X Each X is a 4-bit hexadecimal (16bit two bytes)
        • ABCD:EF01:2345:6789:ABCD:EF01:2345:6789 The leading 0 of X can be omitted
      • 0-bit packed notation
        • In some cases, an IPv6 address may contain a long period of 0 in the middle, and a continuous period of 0 can be compressed into "::". However, in order to ensure the uniqueness of address resolution, "::" in the address can only appear once
        • FF01:0:0:0:0:0:0:1101 → FF01::1101
        • 0:0:0:0:0:0:0:1 → ::1
        • 0:0:0:0:0:0:0:0 → ::
      • Embedded IPv4 address notation
        • In order to realize IPv4-IPv6 interworking, IPv4 addresses will be embedded in IPv6 addresses,
        • At this time, the address is often expressed as: X:X:X:X:X:X:d.d.d.d, the first 96b is expressed in hexadecimal, and the last 32b address is expressed in dotted decimal of IPv4, such as ::192.168. 0.1 and ::FFFF: are two typical examples. Note that in the first 96b, the method of compressing 0 bits is still applicable.
  • subnet mask

    • IP Address & Subnet Mask ==== Network Address
    • IP:
    • Subnet mask:
    • Network address:
    • Local address: 233
    • Generally speaking, the subnet mask of the class A network: The subnet mask of the class B network: The class C network:
  • supernet

    • Re-division of the subnet The first 24 bits are the subnet mask
    • network address: 10 subnet mask (1111 1111 1100 0000 )
    • x.y.z.k:n n subnet mask Indicates that the first n binary bits of the subnet mask are 1, and the last 32-n binary bits are 0

special url

  1. An address where each byte is 0 ("") corresponds to the current host;
  2. An IP address ("") where each byte in the IP address is 1 is the current subnet's broadcast address
  3. All IP addresses start with "11110" Class E IP address Both are reserved for future and experimental use.
  4. The IP address cannot start with decimal "127". The numbers to in this type of address are used for loopback testing, such as: It can represent the IP address of the machine, and you can use "" to test the Web server configured in the machine.
  5. The first 6-bit group of the network ID cannot be set to all "0", and all "0" means the local network.

The port number

Essentially a data of type unsigned short

Logically represents a process that participates in communication

good port

IP address translation

IP address definition

//Base address type All functional interfaces are defined with this type
struct sockaddr{
  	sa_family_t sa_family;    //The value of the address cluster is assigned by macro int
    char sa_data[14];         //contact address

//Local address type Local communication
#include <sys/un.h>
struct sockaddr_un{
    sa_family_t sun_family;
    char  sun_path[];         //Socket file (socket file) path

//Network communication address type ipv4
struct sockaddr_in{
    sa_family_t  sin_family;      //address cluster
    in_port_t    sin_port;        //The port number
    struct in_addr sin_addr;      //ipv4 address

struct in_addr{
  	in_addr_t s_addr;    //32-bit unsigned integer
typedef uint32_t in_addr_t;

struct sockaddr_in6{
  	sa_family_t sin6_family;
    __be16  sin6_port;
    __be32  sin6_flowinfo;
    struct in6_addr  sin6_addr;
    __u32 sin6_scope_id;
struct in6_addr{
    //in_addr_t s_addr;
      	_u8 u6_addr8[16];
        __be16 u6_addr16[8];
        __be32 u6_addr32[4];
    #define s6_addr  in6_u.u6_addr8
    #define s6_addr16 in6_u.u6_add16
    #define s6_addr32 in6_u.u6_add32

IP address translation

  • Write ip address and need to pass address in programming
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

//Can only handle IPv4 addresses
//Convert the IPv4 address format with "" dotted decimal to 0xC0A858E9 (big endian) 0XE958A8C0 (little endian)
int inet_aton(const char *cp, struct in_addr *inp);
in_addr_t inet_addr(const char *cp);
in_addr_t inet_network(const char *cp);
//Converts an IPv4 address from a 32-bit unsigned integer to a dotted decimal IP address
char *inet_ntoa(struct in_addr in);

#include <arpa/inet.h>
//local translation network ip address
int inet_pton(int af, const char *src, void *dst);  
af  Value:
	AF_INET   ipv4          src Dotted decimal dst: memory address of type struct in_addr
	AF_INET6  ipv6          src Colon hex dst: memory address of type struct in6_addr
//Convert network ip address to local ip address
const char *inet_ntop(int af, const void *src,char *dst, socklen_t size);
af Value:
	AF_INET  ipv4    src  struct in_addr Type dst: dotted decimal size:INET_ADDRSTRLEN
	AF_INET6 ipv6    src  struct in6_addr Type size:INET6_ADDRSTRLEN

The port number

  • Essentially an unsigned short type of data 0-65535
  • Logically represents a process that participates in communication
  • The port number needs to be given the network byte order in programming
  • Ports 0-1024 are generally occupied by the system and well-known protocols
    • FTP-21 TELNET-23 WWW-80


  • Big-endian Network byte order Big-endian is always used in the network
  • Little-endian PC terminals basically use little-endian
#include <arpa/inet.h>

uint32_t htonl(uint32_t hostlong);     //home  to  network     l  uint32_t   s uint16_t
uint16_t htons(uint16_t hostshort);
uint32_t ntohl(uint32_t netlong);
uint16_t ntohs(uint16_t netshort);

socket socket

#include <sys/types.h>         
#include <sys/socket.h>

int socket(int domain, int type, int protocol);
//Create socket socket
domain:       address family/domain
	AF_UNIX/AF_LOCAL/AF_FILE   :  local communication
	AF_INET   :  network communication based on ipv4
	AF_INET6  :  network communication based on ipv6
	AF_PACKET :  Network communication based on low-level packet interface
type:		  letter of agreement
	SOCK_STREAM :  Data Stream Protocol TCP Protocol
	SOCK_DGRAM  :  Datagram Protocol UDP Protocol
protocol	: Special communication protocol is generally set to 0
Returns socket descriptor on success, returns on failure-1
  • Socket descriptors are similar to file descriptors, UNIX treats the network as a file
  • Sending data to the network means writing the file, and receiving data from the network means reading the file

Bind communication address

  • socket socket, if you want to communicate, you need to bind to a unique physical address
  • Local communication, network communication communication addresses are different, but the binding method is the same
    • bind parameter struct sockaddr* but actually pass struct sockaddr_un* or struct sockaddr_in * or struct sockaddr_in6 *
#include <sys/types.h>
#include <sys/socket.h>

int bind(int sockfd, struct sockaddr *my_addr, socklen_t addrlen);
Function: Bind the socket socket sockfd to the physical communication address my_addr
	sockfd:  socket the return value of the function
	my_addr: The address memory value of the specific communication is struct sockaddr_un* /struct sockaddr_in * /struct sockaddr_in6 *
    addrlen:  The second parameter points to the memory length of the communication address
Return value: return 0 on success, -1 on failure and set errno

  • Before the socket socket communicates, if the bind function is not called, it will be automatically bound to an ip address and port.

  • In the programming process, the server creates a socket in order to allow the client to connect, so it needs to be explicitly bound to a specific ip and port.

  • In the programming process, the client often does not call the bind function to bind when creating a socket, because the client can bind randomly.

request connection

#include <sys/types.h>       
#include <sys/socket.h>

int connect(int sockfd, const struct sockaddr *addr,socklen_t addrlen);
Function: Let the socket socket connect to the specified communication address, request a connection, connect to the local communication address, and connect to the communication address of the network
Local communication example

The environment is Ubuntu20

Server side code:

#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>

//Socket local communication Data transfer based on socket file

#define SOCK_FILE "my.sock"

int main(int argc,char *argv[]){
	printf("1.server creation socket socket...\n");
	int sockfd = socket(AF_LOCAL,SOCK_DGRAM,0);
	if(sockfd == -1){
		return -1;
	printf("2.socket the socket is associated to socket document...\n");
	struct sockaddr_un addr;   //Local communication address type
	addr.sun_family = AF_LOCAL;     //address family
	strcpy(addr.sun_path,SOCK_FILE);//socket file
	//Create socket file when bound to physical memory	
	int ret = bind(sockfd,(struct sockaddr*)&addr,sizeof(addr));
	if(ret != 0){
		return -1;

	printf("3.The server receives data in a loop...\n");
		char buf[1024] = {};
		ssize_t rb = read(sockfd,buf,sizeof(buf));
		if(rb == -1){
			return -1;
		if(rb == 0){
		printf("recv: %s\n",buf);
	printf("4.The server has finished reading the data,shut down the server!\n");

	printf("5.delete socket file!\n");

    return 0;

Client code:

	* File Name: 05localclient.c
	* Author: unite
	* Tel: 18758077967 
	* Created Time: 2022 Monday September 5th, 15:34:49

#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>

#define SOCK_FILE "my.sock"

int main(int argc,char *argv[]){
	printf("1.Client creates socket...\n");
	int sockfd = socket(AF_LOCAL,SOCK_DGRAM,0);
	if(sockfd == -1){
		return -1;

	printf("2.Client prepares to connect to server socket contact address...\n");
	struct sockaddr_un addr;
	addr.sun_family = AF_LOCAL;
	int ret = connect(sockfd,(const struct sockaddr*)&addr,sizeof(addr));
	if(ret != 0){
		return -1;
	printf("3.Client sends data cyclically...\n");
		char buf[1024] = {};
		int len = strlen(buf);
		if(buf[len-1] == '\n'){
			buf[len] = '\0';
		if((ret = write(sockfd,buf,len+1))<0){
			return -1;
		if(ret == 0 || strcmp(buf,"!quit")==0){
	printf("4.Client: close socket!\n");

    return 0;

final result:

communication mode

  • One-to-one communication (Peer to Peer)

  • One-to-many communication server/client (Server/Client C/S)

    • C/S client/server League of Legends
      • advantage
        • good stability
        • efficient
        • The client caches data in advance, reducing the transmission requirements for server data during operation
      • shortcoming
        • Requires development server and client
        • Additional client installation is required from the user's point of view
        • Update Client also needs to be updated
        • Poor compatibility between server and client
    • B/S browser/server 4399
      • advantage
        • A unified way to access the server, only need to install the browser
        • Good versatility and compatibility
        • Maintenance costs are also relatively low
      • shortcoming
        • poor stability
        • The network delay is relatively large
        • Real-time performance is not very good
        • Data cannot be cached in advance (current browsers have certain caching capabilities)
  • Heterogeneous network model The bottom layer is socket

socket local communication

  • Depends on socket file
  • The advantage of socket local communication is good stability


  • One-to-one network communication
# sudo apt-get install net-tools

# ping         #Test whether the current host and have a network


Tags: TCP/IP network Network Protocol

Posted by ravi_aptech on Tue, 06 Sep 2022 21:37:50 +0530