socket函數
建立一個套接字用于通信
參數:
domain:指定通信協定族(protocol family),常用取值AF_INET(IPv4)
type:指定socket類型, 流式套接字SOCK_STREAM,資料報套接字SOCK_DGRAM,原始套接字SOCK_RAW
protocol:協定類型,常用取值0, 使用預設協定
傳回值:
成功: 傳回非負整數,套接字;
失敗: 傳回-1
bind函數
綁定一個本地位址到套接字
sockfd:socket函數傳回的套接字
addr:要綁定的位址
listen函數
listen函數應該用在調用socket和bind函數之後, 并且用在調用accept之前, 用于将一個套接字從一個主動套接字轉變成為被動套接字。
backlog說明:
對于給定的監聽套接口,核心要維護兩個隊列:
1、已由客戶發出并到達伺服器,伺服器正在等待完成相應的TCP三路握手過程(SYN_RCVD狀态)
2、已完成連接配接的隊列(ESTABLISHED狀态)
但是兩個隊列長度之和不能超過backlog

backlog推薦使用SOMAXCONN(3.13.0-44-generic中該值為128), 使用等待隊列的最大值;
Man-Page中的listen說明:
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.
If the backlog argument is greater than the value in /proc/sys/net/core/somaxconn(Ubuntu 14.04 該值為128), then it is silently truncated to that value; the default value in this file is 128. In kernels
before 2.4.25, this limit was a hard coded value, SOMAXCONN, with the value 128.
accept函數
從已完成連接配接隊列傳回第一個連接配接(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.
sockfd:伺服器套接字
addr:将傳回對等方的套接字位址, 不關心的話, 可以設定為NULL
addrlen:傳回對等方的套接字位址長度, 不關心的話可以設定成為NULL, 否則一定要初始化
傳回值:
On success, these system calls return a non-negative integer that is a descriptor for the accepted
socket. On error, -1 is returned, and errno is set appropriately.
connect函數
建立一個連接配接至addr所指定的套接字
sockfd:未連接配接套接字
addr:要連接配接的套接字位址
addrlen:第二個參數addr長度
示例:echo server/client實作
附-Makefile