网络编程之Sockets Introduction(一)

SOCKETS规范及应用-WINDOWS网络编程接口 Windows   Sockets   规范及应用                           -Windows网络编程接口     ******************************************************************     版权信息             本书作者保留所有版权。禁止任何商业性的转载或复制。非赢利性质的转载和复制不得修改文 阅读详情

前言

一直在想该怎么记录UNP篇,最后我想我要锻炼自己归纳总结的能力,抓重点,抓应用。

1. introdution

本章主要分析了地址结构体的相关API函数,及2进制和字符串形式的地址之间的转化函数,最后这些地址转换函数依赖于具体的IP协议,UNP中提出了自己的以sock_开头的地址转换函数,其不依赖于具体的协议。

  • These structures can be passed in two directions: from the process to the kernel, and from the kernel to the process.
  • The address conversion functions convert between a text representation of an address and the binary value that goes into a socket address structure.
  • these address conversion functions is that they are dependent on
    the type of address being converted: IPv4 or IPv6.

2. Socket Address Structures

2.1 IPv4 Socket Address Structure
struct in_addr {
    in_addr_t s_addr; /* 32-bit IPv4 address */
    /* network byte ordered */
};
struct sockaddr_in {
    uint8_t sin_len; /* length of structure (16) */
    sa_family_t sin_family; /* AF_INET */
    in_port_t sin_port; /* 16-bit TCP or UDP port number */
    /* network byte ordered */
    struct in_addr sin_addr; /* 32-bit IPv4 address */
    /* network byte ordered */
    char sin_zero[8]; /* unused */
};

UNP强调了以下几点:

  • Having a length field simplifies the handling of variable-length socket address structures.
  • Even if the length field is present, we need never set it and need never examine it, unless we are dealing with routing sockets (Chapter 18). It is used within the kernel by the routines that deal with socket address structures from various protocol families (e.g., the routing table code).
  • The POSIX specification requires only three members in the structure: sin_family, sin_addr, and sin_port.
  • Both the IPv4 address and the TCP or UDP port number are always stored in the structure in network byte order.
  • if serv is defined as an Internet socket address structure, then serv.sin_addr references the 32-bit IPv4 address as an in_addr structure, while serv.sin_addr.s_addr references the same 32-bit IPv4 address as an in_addr_t.
  • The sin_zero member is unused, but we always set it to 0 when filling in one of these structures.

显然第一点第二段的内容,不是很容易理解,要到以后的章节结合分析,但是目前只需要掌握其sin_len成员用于处理变长socket地址结构体。还有第4点,可以看到in_addr结构体只包含一个成员in_addr_t,这样引用其32位的地址就有两种方式。

2.2 Generic Socket Address Structure

struct sockaddr {
    uint8_t sa_len;
    sa_family_t sa_family; /* address family: AF_xxx value */
    char sa_data[14]; /* protocol-specific address */
};

之前在APUE也纳闷为什么在给socket函数传递地址结构体指针时,都要强制转换成sockaddr *类型,现在UNP给出了答案:

But any socket function that takes one of these pointers as an argument must deal with socket address structures from any of the supported protocol families. A problem arises in how to declare the type of pointer that is passed. With ANSI C, the solution is simple: void * is the generic pointer type. But, the socket functions predate ANSI C and the solution chosen in 1982 was to define a generic socket address structure in the sys/socket.h header.

为了更深刻的理解,UNP分别从编程人员和内核的角度思考generic socket address structures的意义,特别应注意内核的角度:

  • From an application programmer ’s point of view, the only use of these generic socket address structures is to cast pointers to protocol-specific structures.
  • From the kernel’s perspective, another reason for using pointers to generic socket address structures as arguments is that the kernel must take the caller’s pointer, cast it to a struct sockaddr *, and then look at the value of sa_family to determine the type of the structure.

2.3 IPv6 Socket Address Structure

struct in6_addr {
    uint8_t s6_addr[16]; /* 128-bit IPv6 address */
    /* network byte ordered */
};
#define SIN6_LEN /* required for compile-time tests */
struct sockaddr_in6 {
    uint8_t sin6_len; /* length of this struct (28) */
    sa_family_t sin6_family; /* AF_INET6 */
    in_port_t sin6_port; /* transport layer port# */
    /* network byte ordered */
    uint32_t sin6_flowinfo; /* flow information, undefined */
    struct in6_addr sin6_addr; /* IPv6 address */
    /* network byte ordered */
    uint32_t sin6_scope_id; /* set of interfaces for a scope */
};
  • The IPv6 family is AF_INET6, whereas the IPv4 family is AF_INET.
  • The sin6_flowinfo member is divided into two fields:
  • The low-order 20 bits are the flow label
  • The high-order 12 bits are reserved
  • The sin6_scope_id identifies the scope zone in which a scoped address is
    meaningful, most commonly an interface index for a link-local address.

第二条flow label的作用目前尚且不太清楚,第三条都更加难以理解,可以暂时放置下,等到具体的章节再次分析。

2.4 New Generic Socket Address Structure

struct sockaddr_storage {
    uint8_t ss_len; /* length of this struct (implementation dependent) */
    sa_family_t ss_family; /* address family: AF_xxx value */
    /* implementation-dependent elements to provide:
    * a) alignment sufficient to fulfill the alignment requirements of
    * all socket address types that the system supports.
    * b) enough storage to hold any type of socket address that the
    * system supports.
    */
};

UNP以Generic Socket Address Structure与New Generic Socket Address Structure的区别来介绍:

  • If any socket address structures that the system supports have alignment requirements, the sockaddr_storage provides the strictest alignment requirement.
  • The sockaddr_storage is large enough to contain any socket address structure that the system supports.

非常严格的地址对齐及足够大的空间容纳各种socket address structure,但是笔者觉得现阶段只要记住如何应用就行:

Note that the fields of the sockaddr_storage structure are opaque to the user, except for ss_family and ss_len (if present). The sockaddr_storage must be cast or copied to the appropriate socket address structure for the address given in ss_family to access any other fields.

2.5 Comparison of Socket Address Structures

下图的给出假设了两个前提,第一都包含length,第二其他成员都是按照POSIX要求的最低位数假设。

加个图

UNP中给出以下两点注意的地方:

  • To handle variable-length structures, whenever we pass a pointer to a socket address structure as an argument to one of the socket functions, we pass its length as another argument.
  • The sockaddr_un structure itself is not variable-length (Figure 15.1), but the amount of information — the pathname within the structure—is variable-length. When passing pointers to these structures, we must be careful how we handle the length field, both the length field in the socket address structure itself and the length to and from the kernel.

但是以下的强调的话,却让我不甚理解,感觉和上面矛盾。但是从下文的内容来看,应该以上面的话理解为主。

Had the length field been present with the original release of sockets, there would be no need for the length argument to all the socket functions: the third argument to bind and connect, for example. Instead, the size of the structure could be contained in the length field of the structure.

2.6 Value-Result Arguments

图一:

struct sockaddr_in serv;
/* fill in serv{} */
connect(sockfd, (SA *) &serv, sizeof(serv));

Three functions, bind, connect, and sendto, pass a socket address structure from the process to the kernel. One argument to these three functions is the pointer to the socket address structure and another argument is the integer size of the structure, Since the kernel is passed both the pointer and the size of what the pointer points to, it knows exactly how much data to copy from the process into the kernel.

这里和2.5部分对应,类似bind,connect,sento等函数,都是将地址结构体从进程空间传到内核空间,此时需要两个参数,一个是结构体本身,一个是结构体的大小。

图二:

struct sockaddr_un cli; /* Unix domain */
socklen_t len;
len = sizeof(cli); /* len is a value */
getpeername(unixfd, (SA *) &cli, &len);
/* len may have changed */

Four functions, accept, recvfrom, getsockname, and getpeername, pass a socket address structure from the kernel to the process. Two of the arguments to these four functions are the pointer to the socket address structure along with a pointer to an integer containing the size of the structure.

getpeername函数的第三个参数&len是指针,这样做的原因如下,其实很简单,但是UNP描述的比较复杂:

The reason that the size changes from an integer to be a pointer to an integer is because the size is both a value when the function is called (it tells the kernel the size of the structure so that the kernel does not write past the end of the structure when filling it in) and a result when the function returns (it tells the process how much information the kernel actually stored in the structure). This type of argument is called a value-result argument.

2.7 Byte Ordering Functions

加个图

The terms little-endian and big-endian indicate which end of the multibyte value, the little end or the big end, is stored at the starting address of the value.

需要注意MSB和LSB的定义:分别是最高或者最低比特位。

#include <netinet/in.h>
uint16_t htons(uint16_t host16bitvalue);
uint32_t htonl(uint32_t host32bitvalue);
Both return: value in network byte order
uint16_t ntohs(uint16_t net16bitvalue);
uint32_t ntohl(uint32_t net32bitvalue);
Both return: value in host byte order

比较方便的记住这些函数的方式:

In the names of these functions, h stands for host, n stands for network, s stands for short, and l stands for long.

使用这些函数并不需要关心实际数据存储的方式是大端还是小端,只要保证数据到本地时,调用ntohs,发送数据时调用htons。

When using these functions, we do not care about the actual values (big-endian or little-endian) for the host byte order and the network byte order. What we must do is call the appropriate function to convert a given value between the host and network byte order. On those systems that have the same byte ordering as the Internet protocols (big-endian), these four functions are usually defined as null macros.

另外需要注意以下内容,现在可以先不深入但是提前了解:

Another important convention in Internet standards is bit ordering. In many Internet standards, you will see pictures of packets that look similar to the following (this is the first 32 bits of the IPv4 header from RFC 791):

这里写图片描述

This represents four bytes in the order in which they appear on the wire; the leftmost bit is the most significant. However, the numbering starts with zero assigned to the most significant bit.

2.8 Byte Manipulation Functions

#include <strings.h>
void bzero(void *dest, size_t nbytes);
void bcopy(const void *src, void *dest, size_t nbytes);
int bcmp(const void *ptr1, const void *ptr2, size_t nbytes);
Returns: 0 if equal, nonzero if unequal

以上函数用法如下:

bzero sets the specified number of bytes to 0 in the destination. We often use this function to initialize a socket address structure to 0. bcopy moves the specified number of bytes from the source to the destination. bcmp compares two arbitrary byte strings. The return value is zero if the two byte strings are identical; otherwise, it is nonzero.

#include <string.h>
void *memset(void *dest, int c, size_t len);
void *memcpy(void *dest, const void *src, size_t nbytes);
int memcmp(const void *ptr1, const void *ptr2, size_t nbytes);
Returns: 0 if equal, <0 or >0 if unequal (see text)

同样的上述API的用法如下:

memset sets the specified number of bytes to the value c in the destination. memcpy is similar to bcopy, but the order of the two pointer arguments is swapped. bcopy correctly handles overlapping fields, while the behavior of memcpy is undefined if the source and destination overlap. The ANSI C memmove function must be used when the fields overlap. memcmp compares two arbitrary byte strings and returns 0 if they are identical. If not identical, the return value is either greater than 0 or less than 0, depending on whether the first unequal byte pointed to by ptr1 is greater than or less than the corresponding byte pointed to by ptr2. The comparison is done assuming the two unequal bytes are unsigned chars.

3. 待深入问题

  • 第一个问题就是routing sockets的相关概念?
  • IPv6中flow label的作用和意义?
  • 2.5小节前后矛盾的描述 ?
  • 最后难以理解的Internet standards is bit ordering?
sockets(套接字) sockets(套接字)编程有三种,流式套接字(SOCK_STREAM),数据报套接字(SOCK_DGRAM),原始套接字(SOCK_RAW);基于TCP的socket编程是采用的流式套接字 立即下载

相关推荐

Playwright自动化测试实战:攻克日历时间控件三大策略与Java实现

在Web自动化测试领域,元素定位与交互模拟是核心技术基础,其原理在于通过程序精确识别并操作页面中的DOM元素,以模拟真实用户行为。这项技术的核心价值在于提升测试效率、确保交互逻辑的覆盖度与可靠性,广泛应用于电商、金融、OA等系统的功能验证。日历时间控件作为典型的复杂交互组件,常涉及动态弹出层、多级导航与状态同步,是自动化测试中的常见难点。本文聚焦于使用Playwright工具,针对此类控件深入剖析了三种核心解决策略:从最高效的直接赋值、到全面模拟用户交互的主流方法,再到利用组件特性的混合定位方案,并结合Ja

weixin_28835551的博客 313

Sockets是Windows下网络编程的规范,Windows Sockets是Windows下得到广泛应用的、开放的、支持多种协议的网络编程接口。详细用法讲解如下

C#sockets用法详解。

xzs1955的博客 1235

MaixCAM2 4K AI相机硬件解析与开发实战

嵌入式AI视觉开发中,边缘计算设备的选择直接影响项目落地效果。以NPU为核心的AI加速技术通过专用指令集优化,可在低功耗下实现10+TOPS算力,典型应用包括工业质检、智能门禁等实时场景。MaixCAM2作为新一代4K AI相机,搭载AX630 SoC芯片,其双核Cortex-A53与NPU的异构架构,在运行YOLOv11n模型时可达113FPS,显著优于传统方案。开发时需注意模型量化部署技巧,如INT8量化需500+张校准图片覆盖多光照条件,避免准确率下降。设备扩展性方面,PMOD接口支持热成像、ToF传

weixin_30819085的博客 692

Python Socket编程指南:从入门到实战

本文将详细介绍Python中Socket的用法,包括Socket的概念、基本原理以及如何在Python中使用Socket进行网络编程。通过讲解Socket的基本知识和实际代码示例,读者将学习如何编写客户端和服务端代码,并实现网络通信。最后,通过结果展示,读者将全面掌握Python中Socket的应用场景和实战技巧。

qq_35716085的博客 2万+

Halcon实战:基于图像清晰度自动筛选最佳对焦图片

本文详细介绍了如何使用Halcon实现基于图像清晰度的自动筛选最佳对焦图片技术。通过分析灰度值统计和标准差等核心指标,结合实战代码示例,帮助开发者高效处理工业检测中的对焦问题,提升自动化检测的准确性和效率。

weixin_27015733的博客 444

Allegro中调整差分对等长的步骤介绍

【代码】Allegro中调整差分对等长的步骤介绍。

qq_30882617的博客 3838

操作系统:套接字(Sockets)

摘要:套接字(Sockets)是操作系统中实现网络通信的关键机制,作为进程间的通信端点,它使不同计算机上的进程能够通过网络交互。套接字由IP地址和端口号唯一标识,其中知名端口(0-1023)用于标准服务(如HTTP-80、SSH-22),而临时端口(≥1024)由客户端动态分配。在客户端-服务器系统中,服务器监听固定端口等待连接,客户端通过随机端口发起请求,建立连接后即可双向通信。操作系统通过IP地址路由数据包,根据端口号将数据分发给对应进程,实现精确的进程间网络通信。

2402_88047672的博客 1236

Solidworks转URDF避坑实录:从履带机器人到ROS仿真的完整配置流程

本文详细介绍了将Solidworks履带机器人模型转换为URDF格式并配置ROS仿真的完整流程,重点解析了坐标系设置、复杂关节定义、插件配置等关键步骤中的常见问题与解决方案,帮助开发者高效实现履带机器人在RVIZ和Gazebo中的精确仿真。

weixin_30693683的博客 458

Sockets (套接字)的使用

Sockets (套接字)编程是连接网络上两个节点以相互通信的一种方式。一个套接字(节点)侦听IP上的特定端口,而另一个套接字则连接到另一个。当客户端连接到服务器时,服务器形成侦听器套接字。

u011565038的博客 1272

AI 边缘计算控制器GEAC91

AI 边缘计算控制器GEAC91是AI边缘计算控制器是一款基于 NVIDIA Jetson AGX Xavier处理 器、面向智能边缘计算应用场景的解决方案。

weixin_45905610的博客 1203

13、混合系统的离散与连续交互

本文详细探讨了混合系统中离散事件与连续动态的交互机制,涵盖了建模方法、分析技术、设计挑战以及多种控制策略。通过具体案例研究和操作语义的定义,展示了混合系统在制造业、交通系统、机器人技术和过程控制等领域的广泛应用。文章还介绍了实验仿真、稳定性研究及优化方法,旨在帮助读者全面理解混合系统的设计与控制要点,并为未来智能化和自适应混合系统的发展提供了展望。

5f4d3s2a1q的博客 128

网络编程之Sockets Introduction(二)

1. inet_aton, inet_addr, and inet_ntoa Functions #include &amp;lt;arpa/inet.h&amp;gt; int inet_aton(const char *strptr, struct in_addr *addrptr); Returns: 1 if string was valid, 0 on error in_addr_t inet_a...

LoveStackover的博客 403

基于 ESP32 的智能环境监测与远程报警系统

本系统基于 ESP32 实现了环境数据的采集、远程传输、报警通知功能,硬件成本低、接线简单、代码可直接运行。用户可根据实际需求调整传感器类型(如替换为 PM2.5 传感器、土壤湿度传感器)和功能扩展,适合嵌入式 IoT 入门学习和实际场景应用。通过多轮迭代(如优化低功耗、增加 APP 控制),可进一步提升系统的实用性和稳定性。

weixin_42300449的博客 1025

Introduction to the Peer-to-Peer Sockets Project

http://onjava.com/lpt/a/4421———————————————————————————————————————————————————————————— Published on ONJava.com (http://www.onjava.com/) See this if you're having trouble p...

dianchaozong3657的博客 2243

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

Introduction to the Sockets API

Friday Q&A 2014-03-14: Introduction to the Sockets API by Mike Ash   Network programming is everywhere these days. It's tough to find an iPhone app thatdoesn't use the network for something. We al

fishmai的专栏 473

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

Introduction Sockets to Programming in C using TCP/IP

Introduction Computer Network: hosts, routers, communication channels Hosts run applications Routers forward information Packets: sequence of bytes contain control information e.g. destination host P...

weixin_30718391的博客 323

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

unpv13---Sockets Introduction

1.IPV4套接字地址结构:         struct in_addr{            in_addr_t s_addr;       //32-bit IPV4 adress,网络字节序         }         struct socket_in{           uint8_t sin_len;                     //结构长度

81

Introduction to TCP/IP– Introduction

<br />Introduction to TCP/IP– Introduction<br /> <br />Author    Catalyst Development<br /> <br />Catalyst Development is a recognized leader in Internet component software whose award-winning products are used by thousands of corporate, government and ind

aniasa的专栏 342

UNP读书笔记--Chapter 3 Sockets Introduction

Socket Address Structure Name of socket address structures begin with sockaddr_ and end with a unique suffix for each protocol suite. IPv4 Socket Address Structure IPv4 socket address structure is

Chris.Xiao 824

UNP学习笔记(1)-Sockets Introduction:Socket Address Structure

1、IPv4 Socket Address Structure struct in_addr { in_addr_t s_addr; /* 32-bit IPv4 address */ /* network byte ordered */ }; struct sockadd...

aaaaa851766403的博客 178

java network_Java Network Programming, Third Edition

The new third edition of this highly regarded introduction to Java networking programming has been thoroughly revised to cover all of the 100+ significant updates to Java Developers Kit (JDK) 1.5. It ...

weixin_39717704的博客 170

网络协议之:socket协议详解之Socket和Stream Socket

文章目录简介Socket是什么Stream Socket使用socat创建一个TCP服务器使用ss检查TCP连接使用nc连接socket总结 简介 不管是在普通的网络编程中还是在netty中,都经常会提到一个词叫做socket,好像socket是一个神奇的东西,使用socket我们可以建立客户端到服务器端的连接,并且和进行客户端和服务器端的通讯,那么socket到底是什么呢?它有哪些分类呢?一起来看看吧。 Socket是什么 socket的中文翻译是套接字,个人觉的这个翻译真的是太差劲了,套接字听起来毫无意

程序那些事 9031

WindowsSockets基础—概念

本章重点讲解WindowsSockets的基本知识。协议特征,IP定址,TCP和UDP Socket应用程序所调用的windows Sockets API,套接字选项。Windows Socket应用程序与WindowsSockets的关系上图为Windows Sockets应用程序A与应用程序B进行通信的过程。从用户进程的角度看,这两个应用程序都是通过调用WindowsSocketsAPI来实现...

超越 2691

Java Sockets详解—官方原版

Java Sockets详解

深圳市多克创新科技有限公司 3127

【网络】Sockets(概念+API+TCP/UDP流程)+7层数据流与格式+Socket Examples(hello/ACK/终止符0x1b案例)

本文摘要: 课程内容涵盖OSI七层模型与Socket编程。OSI部分重点讲解数据封装流程(层层加/拆头部)、各层数据单元名称(Frame/Packet/Segment等)及OSI与TCP/IP模型对比。Socket部分详解TCP/UDP通信流程:TCP需按序调用socket-bind-listen-accept等API,UDP则用sendto/recvfrom;区分TCP(可靠流式)与UDP(无连接报文)特性;介绍accept三种服务器模式(迭代/fork/select)及端口管理。辅助API包括字节序转换

weixin_44174312的博客 382

Linux UDP网络编程套接字sockets

在学校我们用学号,相比于身份证更简便,假如我的学号是2211211023,这样就能看到我是22级的,方便阅读信息。但是,这两个结构体都不用,我们用 sockaddr。网络通信的本质是进程间通信,有了 IP 就可以标识公网内唯一的一台主机,想要完成网络通信我们还需要一个东西来标识一台主机上的某个进程,这个标识就是端口号(port)。三种应用场景:网络套接字主要运用于跨主机之间的通信,也能支持本地通信,而域间套接字只能在本地通信,而原始套接字可以跨过传输层(TCP/IP 协议)访问底层的数据。

puppy_1mo的博客 1126
上一篇: 网络编程之Elementary TCP Sockets(二)
下一篇: 网络编程之Sockets Introduction(二)
LoveStackover
博客等级 码龄9年 14粉丝 57原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值