1. 程式人生 > >什麽是網絡套接字(Socket)?

什麽是網絡套接字(Socket)?

ise 通信 function conn linux writing 深入 ket targe

  什麽是網絡套接字(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,詳細請參考維基百科。

什麽是網絡套接字(Socket)?