Socket principle and Programming basics

Source: Internet
Author: User
Tags file transfer protocol htons

First, Socket Introduction

Socket is a way of process communication, that is, some API functions that call this network library implement the data exchange between related processes distributed in different hosts.

Several definitions:

(1) IP address: that is, according to the TCP/IP protocol assigned to the local host network address, two processes to communicate, either process first to know the location of the communication, that is, the other side of the IP.

(2) port number: Used to identify the local communication process, a local process in the communication will occupy a port number, different process port number is different, so before the communication must be assigned a port number that is not accessed.

(3) Connection: Refers to a communication link between two processes.

(4) Semi-related: The network with a ternary group can be globally unique flag a process:

(Protocol, local address, local port number)

Such a ternary group, called a semi-correlation, specifies each half of the connection.

(4) Full correlation: A complete inter-network process communication needs to consist of two processes and can only use the same high-level protocol. That is, it is not possible to communicate at one end with the TCP protocol, and the other end with the UDP protocol. Therefore a complete inter-network communication requires a five-tuple to identify:

(Protocol, local address, local port number, remote address, remote port number)

Such a five-tuple, called a Correlation (association), that is, two protocols of the same semi-correlation can be combined into a suitable correlation, or fully specified to form a connection.

Second, the customer/ Server Mode

In TCP/IP network applications, the main mode of interaction between the two processes of communication is the client/server (Client/server, c/s) mode, that is, the customer sends a service request to the server, and the server receives the request and provides the corresponding service. The client/server model is built based on the following two points:

(1) First, the cause of the network is the network hardware and software resources, computing power and information is not equal, need to share, so as to create a host with a large number of resources to provide services, less resources of Customer request service This non-reciprocal role.

(2) Second, the inter-network process communication is completely asynchronous, the process of communication between the two processes do not have a parent-child relationship, and do not share memory buffer, it is necessary to establish a mechanism for communication between the process of establishing a link between the two data exchange to provide synchronization, which is based on the client/server mode of TCP/IP.

Server-side:

The process is to start the server first and provide the appropriate services on request:

(1) Open a communication channel and inform the local host, it is willing to a certain recognized address on a port (such as the FTP port may be 21) to receive customer requests;

(2) Waiting for customer request to reach the port;

(3) When a service request is received from a client, the request is processed and a response signal is sent. Receives a concurrent service request to activate a new process to handle this customer request (such as fork, exec in a UNIX system). The new process handles this customer request and does not need to respond to other requests. After the service is complete, close the communication link with the customer for this new process and terminate.

(4) Return to step (2) and wait for another customer to request.

(5) shutting down the server

Client:

(1) Open a communication channel and connect to a specific port on the host where the server resides;

(2) Send the service request message to the server, wait for and receive the reply, continue to make the request ...

(3) Close the communication channel and terminate after the request is finished.

From the process described above:

(1) The role of the client and the server process is asymmetric, so the code is different.

(2) The server process is typically started first. As long as the system is running, the service process persists until normal or forced termination.

After introducing the basics, here are some API functions:

Create Socket ──socket ()

Before a socket is used, the application must first have a socket, and the system calls the socket () to provide the application with the means to create the socket, which is called in the following format:

Socket PASCAL FAR socket (int af, int type, int protocol);

The call receives three parameters: AF, type, protocol. Parameter AF specifies the area in which the communication occurs: Af_unix, Af_inet, Af_ns, and so on, while DOS, Windows only supports Af_inet, which is the internetwork zone. Therefore, the address family is the same as the protocol family. The parameter type describes the type of socket to be established. There are three kinds of:

(1) One is the TCP flow socket (SOCK_STREAM) provides a connection-oriented, reliable data transmission service, the error-free, non-repeatable transmission, and in the order of delivery received. Internal flow control to avoid data flow overrun, data is considered as a byte stream, no length limit. File Transfer Protocol (FTP) uses streaming sockets.

(2) The second is the datagram Socket (SOCK_DGRAM) provides a non-connected service. Packets are sent in a separate package, without error-free guarantees, data may be lost or duplicated, and the order of reception is confusing. The Network File system (NFS) uses a datagram socket.

(3) Three is the original socket (SOCK_RAW) that interface allows direct access to lower-level protocols such as IP, ICMP. Often used to verify a new protocol implementation or to access new devices that are configured in an existing service.

The parameter protocol describes the specific protocol used by the socket, and if the caller does not want to specifically specify the protocol used, set to 0, using the default connection mode. Based on these three parameters, a socket is established and the corresponding resource is assigned to it, and an integer socket size is returned. Therefore, the socket () system call actually specifies the "protocol" element in the related five-tuple.

Specify local address ──bind ()

When a socket is created with a socket (), there is a namespace (address family), but it is not named. Bind () Ties the socket address (including the local host address and local port address) to the created socket size, assigning the name to the socket to specify local semi-correlation. Its invocation format is as follows:

int PASCAL far bind (SOCKET s, const struct SOCKADDR FAR * name, int namelen);

The parameter S is the socket descriptor (socket size) returned by the socket () call and not connected. The parameter name is the local address (first name) assigned to the socket s, and its length is variable, and the structure varies with the communication domain. Namelen indicates the length of the name. If no error occurs, bind () returns 0. Otherwise, return socket_error.

Establish socket Connection ──connect () and accept ()

These two system calls are used to complete a complete correlation establishment where connect () is used to establish the connection. The Accept () is used to cause the server to wait for the actual connection from a client process.

The call format for connect () is as follows:

int PASCAL far Connect (SOCKET s, const struct SOCKADDR FAR * name, int namelen);

The parameter S is the local socket descriptor to which the connection is to be established. The parameter name indicates a pointer to the address structure of the other socket. The length of the other socket address is explained by Namelen.

If no error occurs, connect () returns 0. Otherwise the return value is Socket_error. In a connection-oriented protocol, this call causes the connection between the local system and the external system to actually be established.

Because the address family is always included in the first two bytes of the socket address structure and is associated with a protocol family through the socket () call. So bind () and connect () do not require a protocol as a parameter.

The call format for accept () is as follows:

Socket PASCAL far accept (socket s, struct sockaddr far* addr, int far* addrlen);

The parameter s is a local socket descriptor, which should be called before listen () before being used as a parameter to the accept () call. Addr A pointer to the client socket address structure that is used to receive the address of the connection entity. The exact format of the addr is determined by the address family established when the socket was created. Addrlen the length (in bytes) of the client-side socket address. If no error occurs, accept () returns a value of the socket type that represents the descriptor of the received socket. Otherwise the return value is Invalid_socket.

Accept () is used for connection-oriented servers. Parameters addr and Addrlen store the address information of the client party. Before the call, the parameter addr points to an address structure with an initial value of NULL, while the initial value of Addrlen is 0, and after the call to accept (), the server waits for a client connection request from a socket numbered s, and the connection request is made by the client's connect () call. When a connection request arrives, the Accept () call places the first client socket address and length on the request connection queue into addr and Addrlen, and creates a new socket size that has the same characteristics as S. The new socket can be used to process server concurrent requests.

Four sockets system calls, Sockets (), bind (), connect (), accept (), can complete a completely five-dollar related establishment. The socket () specifies the protocol element in a five-tuple, which is used in relation to whether it is a client or server, or whether it is connection-oriented. Bind () specifies a local two-dollar, local host address and port number in a five-tuple, and its usage is related to whether it is connection-oriented: Bind () is called on the server side, regardless of whether it is connection-oriented, or bind () is not called with connection-oriented, and can be done automatically via connect (). With no connection, the client must use BIND () to obtain a unique address.

Monitoring Connection ──listen ()

This call is used to target a connection server, indicating that it is willing to receive connections. Listen () needs to be called before accept (), whose invocation format is as follows:

int PASCAL Far Listen (SOCKET s, int backlog);

The parameter s identifies a locally established, not yet connected socket size, and the server is willing to receive requests from it. The backlog represents the maximum length of the request connection queue and is used to limit the number of queued requests, currently allowing a maximum value of 5. If no error occurs, listen () returns 0. Otherwise it returns SOCKET_ERROR.

Listen () can complete the required connection for socket s that have not called bind () during the call process and establish a backlog-length request connection queue.

Calling Listen () is the third step in the four steps a server receives for a connection request. It allocates a stream socket in the calling socket () and calls bind () to the s assigned to a name, and must be called before accept ().

data Transfer ──send () with recv ()

When a connection is established, the data can be transferred. Common system calls have Send () and recv ().

A send () call is used to send output data on a connected datagram or stream socket specified by S, in the following format:

int PASCAL far Send (SOCKET s, const char far *buf, int len, int flags);

The parameter s is a connected local socket descriptor. The BUF points to a pointer to the buffer that holds the data, which is specified in length by Len. Flags specifies the mode of transmission control, such as whether to send out-of-band data. If no error occurs, send () returns the total number of bytes sent. Otherwise it returns SOCKET_ERROR.

The recv () call is used to receive input data on a connected datagram or stream socket specified by S, in the following format:

int PASCAL far recv (sockets S, char far *buf, int len, int flags);

The parameter s is a connected socket descriptor. The BUF points to the pointer that receives the input data buffer, whose length is specified by Len. Flags specifies the mode of transmission control, such as whether to receive out-of-band data. If no error occurs, recv () returns the total number of bytes received. Returns 0 if the connection is closed. Otherwise it returns SOCKET_ERROR.

Input/ output multiplexing ──select ()

The Select () call is used to detect the state of one or more sockets. For each socket, this call can request information about a read, write, or Error state. A collection of sockets that request a given State is indicated by a fd_set structure. On return, this structure is updated to reflect the subset of sockets that meet certain criteria, and the Select () call returns the number of sockets that meet the criteria, with the following invocation format:

int PASCAL Far Select (Int. Nfds, Fd_set FAR * Readfds, Fd_set FAR * Writefds, Fd_set FAR * exceptfds, const struct TIMEVAL FAR * timeout);

The parameter Nfds indicates the value of the checked socket descriptor, which is generally ignored.

The Readfds parameter points to a pointer to a collection of socket descriptors to be read-tested, which the caller wants to read from. The Writefds parameter points to a pointer to the set of socket descriptors to be write-detected. Exceptfds a pointer to a collection of socket descriptors to detect if an error occurred. Timeout points to the maximum time the Select () function waits, or a blocking operation if set to null. Select () returns the total number of socket descriptors that are prepared in the FD_SET structure, or returns SOCKET_ERROR if an error occurs.

Close Socket ──closesocket ()

Closesocket () Closes the socket S and releases the resources assigned to the socket, and if s involves an open TCP connection, the connection is freed. The invocation format for closesocket () is as follows:

BOOL PASCAL far closesocket (SOCKET s);

parameter s the socket descriptor to be closed. If no error occurs, closesocket () returns 0. Otherwise the return value is Socket_error.

These are some of the common API functions of the socket API, the following is a piece of code:

Client code:

#include <winsock2. H>

#include <stdio.h>

#pragma comment (lib, "Ws2_32.lib")

int main () {

int err;

WORD versionrequired;

Wsadata Wsadata;

Versionrequired=makeword (a);

Err=wsastartup (versionrequired,&wsadata);//version information of the Protocol library

if (!err) {

printf ("Client nested word has been opened!\n");

} else{

printf ("The client's nested word open failed!\n");

Return 0;//End

}

SOCKET Clientsocket=socket (af_inet,sock_stream,0);

Sockaddr_in clientsock_in;

Clientsock_in.sin_addr. S_un. S_ADDR=INET_ADDR ("127.0.0.1");

Clientsock_in.sin_family=af_inet;

Clientsock_in.sin_port=htons (6000);

Bind (Clientsocket, (sockaddr*) &clientsock_in,strlen (sockaddr));//Note the third parameter

Listen (clientsocket,5);

Connect (Clientsocket, (sockaddr*) &clientsock_in,sizeof (sockaddr));//Start connection

Char receivebuf[100];

Recv (clientsocket,receivebuf,101,0);

printf ("%s\n", receivebuf);

Send (Clientsocket, "Hello,this is the client", strlen ("Hello,this is Client") +1,0);

Closesocket (Clientsocket);

WSACleanup ();

return 0;

}

Server-side code:

#include <winsock2. H>

#include <stdio.h>

#pragma comment (lib, "Ws2_32.lib")

int main ()

{

Creating sockets

WORD myversionrequest;

Wsadata Wsadata;

Myversionrequest=makeword (a);

int err;

Err=wsastartup (Myversionrequest,&wsadata);

if (!err) {

printf ("Open socket \ n");

}else

{

Further binding sockets

printf ("Nested Word not open!");

return 0;

}

Socket Sersocket=socket (af_inet,sock_stream,0);//Create a recognizable socket

Parameters that need to be bound

Sockaddr_in addr;

Addr.sin_family=af_inet;

Addr.sin_addr. S_un. S_addr=htonl (Inaddr_any);//IP address

Addr.sin_port=htons (6000);//Bound Port

Bind (Sersocket, (sockaddr*) &addr,sizeof (sockaddr));//bind complete

Listen (sersocket,5);//The second parameter represents the maximum number of connections that can be received

To start listening.

//////////////////////////////////////////////////////////////////////////

Sockaddr_in Clientsocket;

int len=sizeof (SOCKADDR);

while (1)

{

SOCKET serconn=accept (Sersocket, (sockaddr*) &clientsocket,&len);//If this is not accept but conection. It's going to keep listening.

Char sendbuf[100];

sprintf (SendBuf, "Welcome%s to Bejing", Inet_ntoa (CLIENTSOCKET.SIN_ADDR));//find the corresponding IP and print the line to there

Send (Serconn,sendbuf,strlen (SENDBUF) +1,0);

Char receivebuf[100];//receive

Recv (Serconn,receivebuf,strlen (RECEIVEBUF) +1,0);

printf ("%s\n", receivebuf);

Closesocket (serconn);//Close

WSACleanup ();//Release the operation of the resource

}

return 0;

}


Socket principle and Programming basics

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.