在 4.2 BSD UNIX® 操作系统中首次引入,Sockets API 现在是任何操作系统的标准特性。
事实上,很难找到一种不支持 Sockets API 的现代语言。
该 API 相当简单,但新的开发人员仍然会遇到一些常见的隐患。
本文识别那些隐患并向您显示如何避开它们。
捕获并检查每一个返回状态,而不是忽略它们。
int status, sock, mode;
/* Create a new stream (TCP) socket */
sock = socket( AF_INET, SOCK_STREAM, 0 );
...
status = send( sock, buffer, buflen, MSG_DONTWAIT );
if (status == -1)
{ /* send failed */
printf( "send failed: %s\n", strerror(errno) );
}
else
{ /* send succeeded -- or did it? */
}[/td][/tr][/table]
如果数据成功地排到传输队列,则返回 0。如果排队失败,则返回 -1(通过使用 errno 变量可以了解失败的原因)。如果不是所有的字符都能够在函数调用时排队,则最终的返回值是发送的字符数。读取的字节数(最高为您指定的最大值);
或者 -1,表示错误;
或者 0,如果已经到达文件末尾。
int sock, status;
sock = socket( AF_INET, SOCK_STREAM, 0 );
...
status = read( sock, buffer, buflen );
if (status > 0)
{ /* Data read from the socket */
}
else if (status == -1)
{ /* Error, check errno, take action... */
}
else if (status == 0)
{ /* Peer closed the socket, finish the close */ close( sock ); /* Further processing... */
}[/td][/tr][/table]
int sock, ret, on;struct sockaddr_in servaddr;/* Create a new stream (TCP) socket */sock = socket( AF_INET, SOCK_STREAM, 0 ): /* Enable address reuse */
on = 1;
ret = setsockopt( sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on) );
/* Allow connections to port 8080 from any available interface */
memset( &servaddr, 0, sizeof(servaddr) );
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl( INADDR_ANY );
servaddr.sin_port = htons( 45000 );
/* Bind to the address (interface/port) */
ret = bind( sock, (struct sockaddr *)&servaddr, sizeof(servaddr) );[/td][/tr][/table] Endianness 是指内存中字节的排列顺序。高位优先(big endian) 按最高有效字节在前排列,然而 低位优先(little endian) 按照最低有效字节在前排序。
高位优先架构(比如 PowerPC®)比低位优先架构(比如 Intel® Pentium® 系列,其网络字节顺序是高位优先)有优势。这意味着,对高位优先的机器来说,在 TCP/IP 内控制数据是自然有序的。低位优先架构要求字节交换 —— 对网络应用程序来说,这是一个轻微的性能弱点。
回页首
View all TCP sockets currently active$ netstat --tcpView all UDP sockets$ netstat --udpView all TCP sockets in the listening state$ netstat --listeningView the multicast group membership information$ netstat --groupsDisplay the list of masqueraded connections$ netstat --masqueradeView statistics for each protocol$ netstat --statistics[/td][/tr][/table]
Display all traffic on the eth0 interface for the local host
$ tcpdump -l -i eth0 // Show all traffic on the network coming from or going to host plato
$ tcpdump host plato // Show all HTTP traffic for host camus
$ tcpdump host camus and (port http) //View traffic coming from or going to TCP port 45000 on the local host
$ tcpdump tcp port 45000[/td][/tr][/table]
回页首
您可以参阅本文在 developerWorks 全球站点上的 英文原文。
TCP 状态机有 11 个状态。参见 W. Richard Steven 的 illustration from TCP/IP Illustrated, Volume 1 一书。