Socket Programming
Socket programming - Application Programming Interface (API)
Network Programming Interface
Application programming interface API (Application Programming Interface)
Application Programming Interface API: is the control and control of the operating system application process will be a transition system call interface.
Some typical application programming interface :
- Berkeley UNIX operating system defines an API, called socket interface (socket interface), referred to as a socket (socket).
- Microsoft operating system uses its interface to the socket API, a slightly different form of API, and called Windows Socket Interface, WINSOCK.
- AT & T UNIX System V for a defined API, abbreviated as TLI (Transport Layer Interface)
Socket Programming -Socket API Overview
- Originally designed: for BSD UNIX-Berkley, for the TCP / IP protocol stack interfaces
- Currently: de facto industry standard, the vast majority of operating systems support
- The most typical Internet network application API interface
- Communication Model: Client / Server (C / S)
- Inter-application communication process abstraction
Identify communication endpoints (External): IP address + port number
How to operate the system / process management socket (internal)? A: socket descriptor (socket descriptor), a small integer
Socket abstract
Similar to the abstract file when the application process creates a socket, the operating system allocates a data structure to store information about the socket, returned socket descriptor
Address structure
Defined structure sockaddr_in:
structsockaddr_in
{
u_charsin_len; /*地址长度*/
u_charsin_family; /*地址族(TCP/IP:AF_INET)*/
u_shortsin_port; /*端口号*/
structin_addrsin_addr;/*IP地址*/
char sin_zero[8]; /*未用(置0)*/
}
Using TCP / IP protocol suite of network applications endpoint address variable declaration, using the structure sockaddr_in
Socket Programming -Socket API function
Socket API function (WinSock)
//WSAStartup
intWSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData);
//WSACleanup
intWSACleanup(void);
Use Socket application must first call the WSAStartup function before using Socket
- The first parameter indicates the version WinSock program request, wherein the high byte indicate the minor version, the lower byte indicates the major version.
- Hexadecimal integer, for example 0x102 represents version 2.1
- The second argument returns the version information of the actual WinSock
- Structure pointer WSADATA
//使用2.1版本的WinSock的程序代码段
wVersionRequested= MAKEWORD( 2, 1 );
err = WSAStartup( wVersionRequested, &wsaData);
Upon completion of the application using the Socket library request, and finally to call WSACleanup function, unbind and Socket library release system resources occupied Socket Library
sd= socket(protofamily,type,proto);
Create a socket, the operating system returns socket descriptor (SD), the first parameter (protocol family): protofamily = PF_INET (TCP / IP), the second parameter (socket type): type = SOCK_STREAM,SOCK_DGRAM orSOCK_RAW(TCP/IP
the third parameters (protocol number): 0 is the default
//创建一个流套接字的代码段
structprotoent*p;
p=getprotobyname("tcp");
SOCKET sd=socket(PF_INET,SOCK_STREAM,p->p_proto);
Socket service-oriented type of TCP / IP
- TCP: reliable, connection-oriented, byte-stream transmission, point
- UDP: unreliable, connectionless datagram transport
int closesocket(SOCKET sd);
Close a socket descriptor sd, if a plurality of processes share a socket, the socket closesocket reference count by 1, is reduced to 0 is not closed, a process of a multi-threaded socket no use counting, if a thread calls closesocket process will shut down a socket, other threads in the process will not be able to access the socket, the return value: 0: success, SOCKET_ERROR: failure
int bind(sd,localaddr,addrlen);
Binding of a socket local endpoint address: IP address + port number
Parameter: socket descriptor (sd), endpoint address (the localaddr)
Clients generally do not have to call bind function
Server: well-known port number, IP address
int listen(sd,queuesize);
Opposite side stream socket server in listening state, only the server calls, only for connection-oriented stream socket
Setting a connection request queue size (QUEUESIZE)
Return value: 0: Successful SOCKET_ERROR: Failed
connect(sd,saddr,saddrlen);
Call connect the client to make the client socket function (SD) with a specific port socket particular computer (the saddr) a (service) connection, only for the client, the client may be used for TCP UDP client may also be used end, TCP client: establish a TCP connection, UDP client: specify the server endpoint address
newsock= accept(sd,caddr,caddrlen);
Service program function call accept a connection queue taken was at the top of the client request from a client requests a stream socket in a listening state sd, and creates a new socket to create a socket connection channel with the client, only to TCP socket, only for server
The use of the newly created sockets (newsock) to communicate with customers
send(sd,*buf,len,flags);
TCP socket function send (client and server), or call the connect function of UDP client socket
sendto(sd,*buf,len,flags,destaddr,addrlen);
sendto function for the UDP server socket and connect the function is not called UDP client socket
recv(sd,*buffer,len,flags);
UDP server receives client socket recv function receives data from the other end of the TCP connection, or from a function call connect data sent by
recvfrom(sd,*buf,len,flags,senderaddr,saddrlen);
recvfrom function terminal for receiving data from the UDP socket with the server does not call connect function UDP client socket
int setsockopt(intsd, intlevel, intoptname, *optval, intoptlen);
setsockopt () function is used to set the option parameter of the socket sd
int getsockopt(intsd, intlevel, intoptname, *optval, socklen_t*optlen);
a getsockopt () function is used to obtain any type, any state of the current value of the option sockets, and stores the result optval
WSAStartup: initialize the socket library (only WinSock)
WSACleanup: clear / terminate the use of socket library (only WinSock)
socket: create socket connect: "Connect" remote server (client-only)
closesocket: release / Close the socket bind: bind a socket local IP address and port number (typically the client does not)
the listen: opposite side TCP server socket is listening mode, and set the queue size (only TCP server socket)
Accept: accept / extracting a connection request, a new socket is created, the new socket (only for server-side TCP socket)
the recv: receiving data (a TCP client socket or connected mode the UDP socket)
recvfrom: receiving data packets (UDP socket used for non-connected mode)
send: sends data (TCP socket for the client or the UDP socket connected mode)
the sendto: sending data packets (UDP socket used for non-connected mode)
the setsockopt: set socket option parameters
getsockopt: Get socket option parameter
Network byte order
TCP / IP defines a standard binary integer representation of a protocol header: network byte order (network byte order), some parameters Socket API function needs to be stored in network byte order (such as IP address, port number, etc.)
Native byte order can be achieved between the network byte order conversion function
htons: native byte order → network byte order (16bits)
ntohs: → local network byte order byte order (16bits)
htonl: native byte order → network byte order (32bits)
ntohl: local network byte order → byte order (32bits)
Network applications Socket API (TCP) to call basic flow
Socket Programming - Client software design
Resolve the server IP address
The client may use the domain name (e.g.: study.163.com) or IP address (eg: 123.58.180.121) identifies the server, using the IP protocol requires a 32 bit binary IP address, it is necessary to convert the domain name or IP address is a 32-bit IP address
The inet_addr function () dotted-decimal IP address to the IP address conversion 32
Function gethostbyname () domain to achieve IP address conversion 32, it returns a pointer to a pointer structure hostent
Resolution server (well-known) port number
The client may also use the service name (e.g., HTTP) server port identifier, service name needs to be converted to well-known port number, function The getservbyname () returns a pointer to a pointer structure servent
Resolution Protocol No.
The client may use the protocol name (eg: the TCP) specify the protocol, the protocol needs to be converted to name resolution protocol (eg: 6), with getprotobyname function () implement protocol name conversion protocol number, returns a pointer to a pointer structure protoent
TCP Client Software Process
1. Determine the server IP address and port number
2. Create a socket
3. Assign local endpoint address (IP address + port number)
4. Connect server (socket)
5. Follow the application layer protocol for communication
6. Close / releasable connection
UDP Client Software Process
1. Determine the server IP address and port number
2. Create a socket
3. Assign local endpoint address (IP address + port number)
4. Specify the server endpoint address, UDP datagram structure
5. Follow the application layer protocol for communication
6. Close / releasing the socket
Socket programming - server software design
4 types of basic server
- No connection loop (Iterative connectionless) server
- Loop connection-oriented (Iterative connection-oriented) server
- No concurrent connections (Concurrent connectionless) server
- Concurrent connection-oriented (Concurrent connection-oriented) basic types of servers server 4
Connectionless server basic flow loop
1. Create a socket
2. Binding endpoint address (INADDR_ANY + port number)
3 repeatedly receives a request from a client
4. Follow the application layer protocol configuration response message transmitted to the client
Data transmission:
The server can not use the connect () function, connectionless server using the sendto () function to send data packets
Access to customer endpoint address: Call recvfrom () function when receiving data, automatically extract
Connection-oriented server processes the basic cycle
1. Create a (main) socket, bind and well-known port number;
2. Set (main) passive socket listening mode, ready for the server;
3. The call accept () function takes the next connection request (through the main socket), creates a new socket for establishing a connection with the client;
4. Follow the application layer protocol, the client receives the repeated request, constructs and sends a response (via the new socket);
5. After service for a particular client, closes the connection between the client and returns to step 3. The loop connection-oriented server processes the basic
Concurrent basic flow connectionless server
The main thread 1: create a socket, bind and well-known port number;
The main thread 2: repeatedly calls recvfrom () function to receive the next client request, and creates a new thread in response to the client process;
1 child thread: receiving a particular request;
Child thread 2: According to the application layer protocol configuration response message, and calls the sendto () transmission;
Child thread 3: Exit (a sub-thread processing a request after termination)
Concurrent connection-oriented server processes the basic
The main thread 1: Create the (main) socket, bind and well-known port number;
The main thread 2: Set (main) passive socket listening mode, ready for the server;
The main thread 3: repeatedly call accept () function takes the next connection request (through the main socket), and creates a new child thread in response to the client process;
1 child thread: receiving a customer service request (by the newly created socket);
Child thread 2: Following the application layer protocol to interact with a particular customer;
Child thread 3: Turn off / release the connection and exit (thread termination)
example
Connectionless server cycle DAYTIME
Connection-oriented servers concurrently DAYTIME