什么是网络套接字(Socket)?

  什么是网络套接字(Socket)?一时还真不好回答,而且网络上也有各种解释,莫衷一是。下文将以本人所查阅到的资料来说明一下什么是Socket。

Socket定义

  Socket在维基百科的定义:

A network socket is an endpoint of an inter-process communication across a computer network. Today, most communication between computers is based on the Internet Protocol; therefore most network sockets are Internet sockets.

  而在Oracle官网上的定义是:

A socket is one endpoint of a two-way communication link between two programs running on the network. 

  其实他们想表达的都是这个意思:Socket是网络上两个程序双向通讯连接的端点。

  那我们又该如何理解‘端点(endpoint)’一词呢?

  在Unix/Linux中,一切皆文件。那对于这两个操作系统而言,“端点”就是一个特殊的文件,也就是说Socket实际上就是文件。既然Socket是文件,那就可以用“打开open –> 读写write/read –> 关闭close”模式来操作它,一些socket函数就是对其进行的操作(读/写IO、打开、关闭)。更加详细的介绍特摘录自tutorialspoint

Sockets allow communication between two different processes on the same or different machines. To be more precise, it's a way to talk to other computers using standard Unix file descriptors. In Unix, every I/O action is done by writing or reading a file descriptor. A file descriptor is just an integer associated with an open file and it can be a network connection, a text file, a terminal,or something else.
To a programmer, a socket looks and behaves much like a low-level file descriptor. This is because commands such as read() and write() work with sockets in the same way they do with files and pipes.

  对于一个Socket而言,它至少需要3个参数来指定:

  1)通信的目的地址;

  2)使用的传输层协议(如TCP、UDP);

  3)使用的端口号。

Socket类型

  套接字类型是指创建套接字的应用程序要使用的通信服务类型。linux系统支持多种套接字类型,最常用的有以下三种:

  1)SOCK_STREAM:流式套接字,提供面向连接、可靠的数据传输服务,数据按字节流、按顺序收发,保证在传输过程中无丢失、无冗余。TCP协议支持该套接字。

  2)SOCK_DGRAM:数据报套接字,提供面向无连接的服务,数据收发无序,不能保证数据的准确到达。UDP协议支持该套接字。

  3)SOCK_RAW:原始套接字。允许对低于传输层的协议或物理网络直接访问,例如可以接收和发送ICMP报文。常用于检测新的协议。

  详细可参考tutorialspoint

Socket网络层次

  这部分主要参考自《深入浅出Linux工具与编程》(余国平著)。

  下图画出了套接字位于网络中的层次,它位于传输层以上、应用层以下。Socket编程正是通过一系列系统调用(Socket API)来完成应用层协议(如ftp、http)。

  

  图:套接字层次图

  套接字是对网络中应用层进程之间的通信进行了抽象,提供了应用层进程利用网络协议栈交换数据的机制。

Socket API

  这里的Socket API指的是Berkeley Sockets API,详细请参考维基百科

原文地址:https://www.cnblogs.com/feng9exe/p/8185820.html