您的位置:首页 > 理论基础 > 计算机网络

Berkeley Socket API – Creating a TCP/IP Server in C

2011-09-10 18:56 417 查看

Berkeley Socket API – Creating a TCP/IP Server in C

Programming Languages

C

API

Berkeley Socket API

What are sockets?

“In computer networking, an Internet socket (or commonly, a network socket or socket) is the endpoint of a bidirectional inter-process communication flow across an Internet Protocol-based computer network, such as the Internet. Internet sockets (in plural) are an application programming interface (API) application program and the TCP/IP stack, usually provided by the operating system. Internet sockets constitute a mechanism for delivering incoming data packets to the appropriate application process or thread, based on a combination of local and remote IP addresses and port numbers. Each socket is mapped by the operational system to a communicating application process or thread.”

in Wikipedia

Data Structure used to store socked details

Data Structure used to store a time value

Used on ‘select’ for timeouts

Filling the socket address

Creating the socket

domain

AF_UNIX – UNIX internal protocols
AF_INET – ARPA Internet protocols
AF_ISO – ISO protocols
AF_NS – Xerox Network Systems protocols
AF_IMPLINK – IMP host at IMP link layer

Type

SOCK_STREAM – provides sequenced, reliable, two-way connection based byte streams
SOCK_DGRAM – connectionless, unreliable messages of a fixed (typically small) maximum length
SOCK_RAW – sockets provide access to internal network protocols and interfaces
SOCK_SEQPACKET – provide a sequenced, reliable, two-way connection-based data transmission path for datagrams of fixed maximum length
SOCK_RDM – Not implemented

Returns

0 – Error
1+ – Socket descriptor

Bind the socket

socket – Socket descriptor
address – Socket address (address, port, family…)
address_len – Structure address size

Listen on socket

socket – Socket descriptor
backlog – Maximum pending connections on queue

Returns

0 – OK
-1 – Error

Wait for socket to be ready

ndfs – number of descriptors
readfds – ‘set’ of descriptors to read from
writefds – ‘set’ of descriptors to write to
errorfds – ‘set’ of descriptors to expect errors from
timeout – time to wait before giveout a timeout

Returns

1+ – Socket descriptor
0 – Timeout
-1 – Error

Accepting an incoming connection

socket – Socket descriptor
address – Socket address (address, port, family…)
address_len – Structure address size

Returns

1+ – Descriptor of the new socket
-1 – Error

Read and write from a socket

It works exactly like when we’re reading from a file, pipe, etc.

Read from socket

Write to socket

The server code revealed

http://www.silviosilva.com/2009/07/15/berkeley-socket-api-creating-a-tcpip-server-in-c/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐