Linux 网络编程 + 笔记

news2024/9/27 12:14:46

协议:一组规则

分层模型结构:

  • OSI七层模型:物理层、数据链路层、网络层、传输层、会话层、表示层、应用层
  • TCP/IP 4层模型:链路层/网络接口层、网络层、传输层、应用层
    • 应用层:http、ftp、nfs、ssh、telnet、
    • 传输层:TCP、UDP
    • 网络层:IP、ICMP、IGMP
    • 链路层:以太网帧协议、ARP

C/S模型和B/S模型

  • C/S模型:client-server
  • B/S模型:browser-server

网络传输流程:

  • 数据没有封装之前,是不能在网络中传递
  • 数据-》应用层-》传输层-》网络层-》链路层  --- 网络环境

以太网帧协议:

  • ARP协议:根据IP地址获取mac地址
  • 以太网帧协议:根据mac地址,完成数据包传输

IP协议:

  • 版本: IPv4、IPv6  -- 4位
  • TTL:time to live (设置数据包在路由节点中的跳转上限,每经过一个路由节点,该值-1, 减为0的路由,有义务将该数据包丢弃)
  • 源IP:32位 -- 4字节 
192.168.1.108 --- 点分十进制 IP地址(string)
  • 目的IP:32位--- 4字节

IP地址:可以在网络环境中,唯一标识一台主机

端口号:可以进行网络通信的一台主机上,唯一标识一个进程

IP地址+端口号:可以在网络环境中,唯一标识一个进程

UDP协议

    16位:源端口号     2^16 = 65536
    
    16位:目的端口号

TCP协议

    16位:源端口号     2^16 = 65536

    16位:目的端口号
    
    32序号
    
    32确认序号
    
    6个标志位

    16位窗口大小       2^16 = 65536

网络套接字:socket

  • 一个文件描述符指向一个套接字(该套接字内部由内核借助两个缓冲区实现)
  • 在通信过程中,套接字一定是成对出现的

网络字节序:

  • 小端法:(pc本地存储)    高位存高地址,低位存低地址            int a = 0x12345678
  • 大端法:(网络存储)        高位存低地址,低位存高地址         
    htonl --> 本地--》网络 (IP)			192.168.1.11 --> string --> atoi --> int --> htonl --> 网络字节序

	htons --> 本地--》网络 (port)

	ntohl --> 网络--》 本地(IP)

	ntohs --> 网络--》 本地(Port)

 注意:htonl --> 本地 --> 网络(IP)

192.168.1.11 --> string --> atoi --> int --> htonl --> 网络字节序

IP地址转换函数

  1. inet_pton
  2. inet_ntop
  • 本地字节序(string IP) ---> 网络字节序 
// 本地字节序(string IP) ---> 网络字节序
int inet_pton(int af, const char *src, void *dst);
    af: AF_INET,AF_INET6
    src:传入,IP地址(点分十进制)
    dst:传出转换后的 网络字节序的 IP地址
    返回值:
	    成功:   1
	    异常:   0,说明src指向的不是一个有效的ip地址
		失败:  -1
NAME
       inet_pton - convert IPv4 and IPv6 addresses from text to binary form

SYNOPSIS
       #include <arpa/inet.h>

       int inet_pton(int af, const char *src, void *dst);

DESCRIPTION
       This  function converts the character string src into a network address
       structure in the af address family, then  copies  the  network  address
       structure  to dst.  The af argument must be either AF_INET or AF_INET6.
       dst is written in network byte order.
  • 网络字节序  ---> 本地字节序(string IP) 
// 网络字节序  ---> 本地字节序(string IP)
const char *inet_ntop(int af, const void *src,char *dst, socklen_t size);
    af: AF_INET,AF_INET6
    src: 网络字节序IP地址
    dst: 本地字节序(string IP)
    size: dst的大小
    返回值: 
        成功: dst
        失败: NULL
NAME
       inet_ntop - convert IPv4 and IPv6 addresses from binary to text form

SYNOPSIS
       #include <arpa/inet.h>

       const char *inet_ntop(int af, const void *src,
                             char *dst, socklen_t size);

DESCRIPTION
       This  function  converts  the  network  address  structure src in the af
       address family into a character string.  The resulting string is  copied
       to  the buffer pointed to by dst, which must be a non-null pointer.  The
       caller specifies the number of bytes available in  this  buffer  in  the
       argument size.
  • sockaddr地址结构: IP + Port  --> 在网络环境中唯一标识一个进程 
sockaddr地址结构: IP + Port  --> 在网络环境中唯一标识一个进程
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(8080);
#if 0
    int dst;
    inet_pton(AF_INET,"192.168.1.100",(void*)dst);   
    addr.sin_addr.s_addr = dst;
#else
    // 取出系统中有效的任意IP地址(二进制类型)
    addr.sin_addr.s_addr =  htonl(INADDR_ANY);
    bind(fd,(struct sockaddr*)&addr,sizeof(addr));

  • socket函数,创建一个套接字
socket函数
    #include <sys/socket.h>
    // 创建一个套接字
    int socket(int domain, int type, int protocol);
    domain: AF_INET,AF_INET6
    type: SOCK_STREAM,SOCK_DGRAM
    protocol: 0
    返回值:
        成功: 新套接字所对应文件描述符
        失败: -1 errno
NAME
       socket - create an endpoint for communication

SYNOPSIS
       #include <sys/types.h>          /* See NOTES */
       #include <sys/socket.h>

       int socket(int domain, int type, int protocol);

DESCRIPTION
       socket()  creates  an  endpoint  for  communication  and  returns a file
       descriptor that refers to that endpoint.  The file  descriptor  returned
       by  a  successful  call  will be the lowest-numbered file descriptor not
       currently open for the process.
  • bind函数 
#include <arpa/inet.h>
int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
    sockfd: socket 函数返回值
    
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(8080);
    addr.sin_addr.s_addr = htonl(INADDR_ANY);

    addr:传入参数(struct sockaddr*)&addr
    addrlen:sizeof(addr) 地址结构的大小
    返回值:
        成功: 0
        失败: -1 errno
NAME
       bind - bind a name to a socket

SYNOPSIS
       #include <sys/types.h>          /* See NOTES */
       #include <sys/socket.h>

       int bind(int sockfd, const struct sockaddr *addr,
                socklen_t addrlen);

DESCRIPTION
       When  a  socket  is  created  with  socket(2), it exists in a name space
       (address family) but has no address assigned to it.  bind() assigns  the
       address specified by addr to the socket referred to by the file descrip‐
       tor sockfd.  addrlen specifies the size, in bytes, of the address struc‐
       ture  pointed  to  by  addr.   Traditionally,  this  operation is called
       “assigning a name to a socket”.

       It is normally necessary to assign a local address using bind() before a
       SOCK_STREAM socket may receive connections (see accept(2)).
  • listen函数,设置同时与服务器建立连接的上限数(同时进行3次握手的客户端数量)
// 设置同时与服务器建立连接的上限数(同时进行3次握手的客户端数量)
int listen(int sockfd, int backlog);
    sockfd: socket 函数返回值
    backlog: 上限数值,最大值为128
    返回值:
        成功: 0
        失败: -1 errno
NAME
       listen - listen for connections on a socket

SYNOPSIS
       #include <sys/types.h>          /* See NOTES */
       #include <sys/socket.h>

       int listen(int sockfd, int backlog);

DESCRIPTION
       listen()  marks  the  socket  referred to by sockfd as a passive socket,
       that is, as a socket that will be used  to  accept  incoming  connection
       requests using accept(2).

       The sockfd argument is a file descriptor that refers to a socket of type
       SOCK_STREAM or SOCK_SEQPACKET.

       The backlog argument defines the maximum length to which  the  queue  of
       pending  connections  for  sockfd  may  grow.   If  a connection request
       arrives when the queue is full, the client may receive an error with  an
       indication  of  ECONNREFUSED  or,  if  the  underlying protocol supports
       retransmission, the request may be ignored so that a later reattempt  at
       connection succeeds.
  • accept函数,阻塞等待客户端建立连接,成功的话,返回一个与客户端成功连接的socket文件描述符
// 阻塞等待客户端建立连接,成功的话,返回一个与客户端成功连接的socket文件描述符
int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
    sockfd:socket 函数返回值
    addr:传出参数,成功与服务器建立连接的那个客户端的地址结构(IP+port)
        socklen_t client_addr_len = sizeof(addr);
        addrlen:传入传出  &client_addr_len
                 入:addr的大小  
                 出:客户端addr实际大小
        返回值:
            成功:能与客户端进行数据通信的 socket 对应的文件描述
            失败:-1,errno
NAME
       accept, accept4 - accept a connection on a socket

SYNOPSIS
       #include <sys/types.h>          /* See NOTES */
       #include <sys/socket.h>

       int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);

       #define _GNU_SOURCE             /* See feature_test_macros(7) */
       #include <sys/socket.h>

       int accept4(int sockfd, struct sockaddr *addr,
                   socklen_t *addrlen, int flags);

DESCRIPTION
       The  accept()  system  call is used with connection-based socket types (SOCK_STREAM, SOCK_SEQPACKET).  It extracts
       the first connection request on the queue of pending connections for the listening socket, sockfd, creates  a  new
       connected  socket, and returns a new file descriptor referring to that socket.  The newly created socket is not in
       the listening state.  The original socket sockfd is unaffected by this call.
  • connect函数
int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
    sockfd: socket 函数返回值

    struct sockaddr_in server_addr; // 服务器地址结构
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(8080);
    inet_pton(AF_INET, "服务器IP地址", &server_addr.sin_addr.s_addr);

    addr:传入参数,服务器的地址结构
    addrlen:服务器的地址结构的大小

    返回值:
        成功: 0
        失败: -1,errno

    如果不使用bind绑定客户端地址结构,采用"隐式绑定".
NAME
       connect - initiate a connection on a socket

SYNOPSIS
       #include <sys/types.h>          /* See NOTES */
       #include <sys/socket.h>

       int connect(int sockfd, const struct sockaddr *addr,
                   socklen_t addrlen);

DESCRIPTION
       The  connect()  system  call connects the socket referred to by the file
       descriptor sockfd to the address specified by addr.  The  addrlen  argu‐
       ment  specifies  the size of addr.  The format of the address in addr is
       determined by the address space of the socket sockfd; see socket(2)  for
       further details.

       If  the socket sockfd is of type SOCK_DGRAM, then addr is the address to
       which datagrams are sent by default, and the  only  address  from  which
       datagrams  are  received.   If  the  socket  is  of  type SOCK_STREAM or
       SOCK_SEQPACKET, this call attempts to make a connection  to  the  socket
       that is bound to the address specified by addr.

       Generally,  connection-based protocol sockets may successfully connect()
       only once; connectionless protocol sockets may  use  connect()  multiple
       times  to change their association.  Connectionless sockets may dissolve
       the association by connecting to an address with the sa_family member of
       sockaddr set to AF_UNSPEC (supported on Linux since kernel 2.2).

TCP 通信流程分析: 

TCP 通信流程分析:
    Server:
        1.socket()      创建socket
        2.bind()        绑定服务器地址结构
        3.listen()      设置同时与服务器建立连接的上限数(监听上限)
        4.accept()      阻塞监听客户端连接
        5.read(fd)      读socket获取客户端数据
        6.小 -- 大写     toupper()
        7.write(fd)     
        8.close()


    Client:
        1.socket()       创建socket
        2.connect()      与服务器建立连接
        3.write()        写数据到socket
        4.read()         读转换后的数据
        5.显示读取结果
        6.close()

未完待续~ 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1429711.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【24美赛思路已出】2024年美赛A~F题解题思路已出 | 无偿自提

A题&#xff1a;资源可用性和性别比例 问题一&#xff1a; 涉及当灯鱼种群的性别比例发生变化时&#xff0c;对更大的生态系统产生的影响。为了分析这个问题&#xff0c;可以采用以下的数学建模思路&#xff1a;建立灯鱼种群模型&#xff1a; 首先&#xff0c;建立一个灯鱼种群…

爬虫入门到精通_基础篇4(BeautifulSoup库_解析库,基本使用,标签选择器,标准选择器,CSS选择器)

1 Beautiful说明 BeautifulSoup库是灵活又方便的网页解析库&#xff0c;处理高效&#xff0c;支持多种解析器。利用它不用编写正则表达式即可方便地实线网页信息的提取。 安装 pip3 install beautifulsoup4解析库 解析器使用方法优势劣势Python标准库BeautifulSoup(markup,…

Session与Cookie、部署redis、redis基本操作、Session共享

1 案例1&#xff1a;PHP的本地Session信息 1.1 问题 通过Nginx调度器负载后端两台Web服务器&#xff0c;实现以下目标&#xff1a; 部署Nginx为前台调度服务器调度算法设置为轮询后端为两台LNMP服务器部署测试页面&#xff0c;查看PHP本地的Session信息 1.2 方案 实验拓扑…

亚马逊新店铺视频怎么上传?视频验证失败怎么办?——站斧浏览器

亚马逊新店铺视频怎么上传&#xff1f; 登录亚马逊卖家中心&#xff1a;首先&#xff0c;卖家需要登录亚马逊卖家中心。在登录后&#xff0c;可以点击左侧导航栏上的“库存”选项&#xff0c;然后选择“新增或管理商品”。 选择商品&#xff1a;接下来&#xff0c;在“新增或…

如何部署Node.js服务并实现无公网ip远程访问本地项目【内网穿透】

文章目录 前言1.安装Node.js环境2.创建node.js服务3. 访问node.js 服务4.内网穿透4.1 安装配置cpolar内网穿透4.2 创建隧道映射本地端口 5.固定公网地址 前言 Node.js 是能够在服务器端运行 JavaScript 的开放源代码、跨平台运行环境。Node.js 由 OpenJS Foundation&#xff0…

YOLOv8进阶 | 如何用yolov8训练自己的数据集(以安全帽佩戴检测举例)

前言&#xff1a;Hello大家好&#xff0c;我是小哥谈。YOLOv8是一种目标检测算法&#xff0c;它是YOLO&#xff08;You Only Look Once&#xff09;系列算法的最新版本。本节课就带领大家如何基于YOLOv8来训练自己的目标检测模型&#xff0c;本次作者就以安全帽佩戴检测为案例进…

二叉树的最小深度

给定一个二叉树&#xff0c;找出其最小深度。 最小深度是从根节点到最近叶子节点的最短路径上的节点数量。 说明&#xff1a;叶子节点是指没有子节点的节点。 示例 1&#xff1a; 输入&#xff1a;root [3,9,20,null,null,15,7] 输出&#xff1a;2示例 2&#xff1a; 输入&…

postgres:锁申请

什么是弱锁&#xff0c;强锁&#xff1f; 为了提高并发控制&#xff0c;PG通过将锁信息在本地缓存&#xff08;**LOCALLOCK**&#xff09;和快速处理常见锁&#xff08;fastpath&#xff09;&#xff0c;减少了对共享内存的访问&#xff0c;提高性能。从而出现了弱锁和强锁的概…

如何在win系统部署开源云图床Qchan并无公网ip访问本地存储图片

文章目录 前言1. Qchan网站搭建1.1 Qchan下载和安装1.2 Qchan网页测试1.3 cpolar的安装和注册 2. 本地网页发布2.1 Cpolar云端设置2.2 Cpolar本地设置 3. 公网访问测试总结 前言 图床作为云存储的一项重要应用场景&#xff0c;在大量开发人员的努力下&#xff0c;已经开发出大…

【自然语言处理】P2 PyTorch 基础 - 张量

目录 安装 PyTorch张量创建张量操作张量索引、切片、联合操作 CUDA张量 本系列博文我们将使用 PyTorch 来实现深度学习模型等。PyTorch 是一个开源的、社区驱动的深度学习框架。拥有强大的工具和库生态系统&#xff0c;包含 TorchVision&#xff08;用于图像处理&#xff09;、…

后端软件三层架构

一、三层架构简介 三层架构是软件开发中广泛采用的一种经典架构模式&#xff0c;其核心价值在于通过清晰的任务划分来提高代码的可维护性和重用性。具体来说&#xff0c;三层架构主要包括以下三个层次&#xff1a; 持久层&#xff08;DAO层&#xff09;&#xff1a;这一层主要…

和鲸科技与智谱AI达成合作,共建大模型生态基座

近日&#xff0c;上海和今信息科技有限公司&#xff08;简称“和鲸科技”&#xff09;与北京智谱华章科技有限公司&#xff08;简称“智谱AI”&#xff09;签订合作协议&#xff0c;双方将携手推动国产通用大模型的广泛应用与行业渗透&#xff0c;并积极赋能行业伙伴探索领域大…

10:00进去,10:06就出来了,面试问的问题真难。。。

&#x1f345; 视频学习&#xff1a;文末有免费的配套视频可观看 &#x1f345; 关注公众号【互联网杂货铺】&#xff0c;回复 1 &#xff0c;免费获取软件测试全套资料&#xff0c;资料在手&#xff0c;涨薪更快 刚从小厂出来&#xff0c;没想到在另一家公司我又寄了。 在这家…

在线JSON转CSV工具

在线JSON转CSV - BTool在线工具软件&#xff0c;为开发者提供方便。本工具可以在浏览器本地将JSON转换成CSV文件,并下载转换后的CSV文件。https://www.btool.cn/json-to-csv 在大数据时代&#xff0c;数据处理与交换已经成为日常工作生活中的常态。而JSON和CSV作为两种广…

Go语言的100个错误使用场景(21-29)|数据类型

前言 大家好&#xff0c;这里是白泽。 《Go语言的100个错误以及如何避免》 是最近朋友推荐我阅读的书籍&#xff0c;我初步浏览之后&#xff0c;大为惊喜。就像这书中第一章的标题说到的&#xff1a;“Go: Simple to learn but hard to master”&#xff0c;整本书通过分析100…

Flutter向 开发人员需要了解的和颜色有关的知识

前言 构建应用前台的开发人员常常需要和颜色打交道&#xff0c;即使很多时候&#xff0c;前台人员不用自己设计颜色&#xff0c;而是由设计师给出颜色&#xff0c;不过经常和颜色打交道&#xff0c;整理和颜色有关的知识还是开卷有益的 flutter中指定颜色的常用方式 Color.f…

海外IP代理:解锁网络边界的实战利器

文章目录 引言&#xff1a;正文&#xff1a;一、Roxlabs全球IP代理服务概览特点&#xff1a;覆盖范围&#xff1a;住宅IP真实性&#xff1a;性价比&#xff1a;在网络数据采集中的重要性&#xff1a; 二、实战应用案例一&#xff1a;跨境电商竞品分析步骤介绍&#xff1a;代码示…

vscode的ssh忽然连不上服务器:远程主机可能不符合glibc和libstdc++ VS Code服务器的先决条件

vscode自动更新了一下就发现连不上服务器了&#xff0c;我寻思估计一大堆人都寄了&#xff0c;一搜&#xff0c;果然哈哈哈哈 然后我直接搜一天内新发布的博客&#xff0c;还真给我搜到了这个问题&#xff0c;按照这个问题里面的回答&#xff08;vscode1.86无法远程连接waitin…

Notion 开源替代品:兼容 Miro 绘图 | 开源日报 No.162

toeverything/AFFiNE Stars: 25.6k License: NOASSERTION AFFiNE 是下一代知识库&#xff0c;将规划、排序和创建集于一身。它是一个注重隐私、开源、可定制且即插即用的替代方案&#xff0c;可以与 Notion 和 Miro 相媲美。主要功能和优势包括&#xff1a; 超融合&#xff1…

深入理解网络编程之BIO和NIO

目录 原生JDK网络编程BIO BIO通信模型服务端代码 BIO通信模型客户端代码 伪异步模型服务端代码&#xff08;客户端跟之前一致&#xff09; 原生JDK网络编程NIO 什么是NIO&#xff1f; NIO和BIO的主要区别 阻塞与非阻塞IO NIO之Reactor模式 NIO中Reactor模式的基本组成…