分类: LINUX
2011-05-12 09:03:05
不管进程是否运行于同一台电脑,他们之间的通信是靠一个叫socket接口来实现的。socket 编程接口可以使用各种不同的网络协议来进行通信。但此处我们限制在讨论用TCP/IP协议来实现的情况。
一个通信端点(end-point)抽象成为一个socket,应用程序使用socket descriptor来访问socket,这如同文件描述符的作用一样。许多用来操作文件描述符的函数也可以用来操作socket描述符,比如write,read等。
创建一个socket的方法:
#include |
Returns: file (socket) descriptor if OK, 1 on error |
其中domain参数:
Domain |
Description |
---|---|
AF_INET |
IPv4 Internet domain |
AF_INET6 |
IPv6 Internet domain |
AF_UNIX |
UNIX domain (有些系统此处用AF_LOCAL) |
AF_UNSPEC |
unspecified |
type参数:
Type |
Description |
---|---|
SOCK_DGRAM |
fixed-length, connectionless, unreliable messages |
SOCK_RAW |
datagram interface to IP (optional in POSIX.1) |
SOCK_SEQPACKET |
fixed-length, sequenced, reliable, connection-oriented messages |
SOCK_STREAM |
sequenced, reliable, bidirectional, connection-oriented byte streams |
The protocol argument is usually zero, to select the default protocol for the given domain and socket type. When multiple protocols are supported for the same domain and socket type, we can use the protocol argument to select a particular protocol. The default protocol for a SOCK_STREAM socket in the AF_INET communication domain is TCP (Transmission Control Protocol). The default protocol for a SOCK_DGRAM socket in the AF_INET communication domain is UDP (User Datagram Protocol).
With a datagram (SOCK_DGRAM) interface, no logical connection needs to exist between peers for them to communicate. All you need to do is send a message addressed to the socket being used by the peer process.