"Socket Programming" chapter One

Source: Internet
Author: User
Tags htons

Reference from:http://www.cnblogs.com/skynet/archive/2010/12/12/1903949.html (Wu Qin)




1, Socket Introduction


There are several methods for local interprocess communication (IPC):

1) Message Delivery (PIPE, FIFO, message queue, etc.)
2) Synchronization (mutex, condition variable, read/write lock, Record lock, semaphore, etc.)
3) Shared memory (anonymous and named)
4) Remote Procedure call (Solaris Gate and Sun RPC)


A process can be identified locally through the process PID, but this is not feasible in the network. In fact, the TCP/IP protocol family has helped us solve this problem, the network layer "IP address" can uniquely identify the host in the network, and the Transport Layer "protocol + port" can uniquely identify the host application (process). By using triples (IP address, Protocol, port), the process of the network can be identified, and the process communication in the network can use this flag to interact with other processes.

For now, almost all applications are network-programmed using sockets.

Self-study in the process of discovering this online classroom, but also good ~

http://www.hubwiz.com/course/56f9ee765fd193d76fcc6c17/("Introduction to Linux Network Programming" by Hui Zhi Network)





2, Socket basic operation


The socket is an implementation of the "Open-write/read-close" mode, and the socket provides the function interface for these operations. The following is an example of TCP, which introduces several basic socket interface functions.



2.1 Socket ()


#include <sys/socket.h>int socket (int domain, int type, int protocol);

The socket () function corresponds to the open operation of a normal file. The open operation of a normal file returns a file descriptor, and the socket () is used to create a socket descriptor (socket descriptor), which uniquely identifies a socket. The three parameters of the socket function are:

1) Domain: That is, the protocol domain, also known as the Protocol family (Address Family). Common protocol families areaf_inet,af_inet6,af_local(or af_unix, UNIX domain sockets),Af_route Wait a minute. The protocol family determines the socket address type, must use the corresponding address in the communication, such as Af_inet decided to use the IPv4 address (32 bits) and the port number (16 bit) combination, Af_unix decided to use an absolute path name as the address.

2) Type: Specifies the socket type. Common socket types are:sock_stream (streaming service, applicable TCP protocol),sock_dgram (packet service, using UDP protocol),sock_raw,sock_ PACKET,sock_seqpacket and so on.

3) Protocol: Therefore, the name of meaning, is the designation of the agreement. Commonly used protocols are,ipproto_tcp,ipproto_udp,ipproto_sctp,ipproto_tipc , etc., they correspond to the TCP transport Protocol, UDP transport Protocol, SCTP Transport Protocol, TIPC transport protocol.

Note: Not the above type and protocol can be arbitrarily combined, such as Sock_stream can not be combined with ipproto_udp . When protocol is 0 o'clock, the default protocol corresponding to type types is automatically selected. Function execution successfully returns a socket file descriptor, failure return-1

When we call the socket to create a socket, the returned socket descriptor exists in the Protocol family (address family,af_xxx) space, but does not have a specific address. If you want to assign an address to it, you must call the bind () function, or the system will automatically randomly allocate a port when you call Connect (), listen ().




2.2 Bind ()


As mentioned above, the bind () function assigns a specific address in the address family to the socket. For example, the corresponding af_inet,af_inet6 is to assign a IPv4 or IPv6 address and port number combination to the socket.

#include <sys/socket.h>int bind (int sockfd, const struct SOCKADDR *addr, socklen_t Addrlen);

The three parameters of a function are:

1) SOCKFD: The socket descriptor, which is created by the socket () function to identify a unique socket. The bind () function is to bind an address to this descriptor.

2) addr: A const struct SOCKADDR * Pointer that points to the Protocol address to bind to SOCKFD. This address structure differs depending on the address protocol family at the time the socket was created.

IPv4 corresponds to:

struct SOCKADDR_IN {    sa_family_t    sin_family;/* Address family:af_inet */    in_port_t      sin_port;   /* port in Network byte order */    struct in_addr sin_addr;   /* Internet address */};/* Internet address. */struct in_addr {    uint32_t       s_addr;     /* address in network byte order */};



IPv6 corresponds to:

struct SOCKADDR_IN6 {     sa_family_t     sin6_family;   /* AF_INET6 */     in_port_t       sin6_port;     /* Port number */     uint32_t        sin6_flowinfo;/* IPV6 Flow information */     struct in6_addr sin6_addr;     /* IPV6 Address     *        /uint32_t sin6_scope_id;/* Scope ID (new in 2.4) */};struct in6_addr {     unsigned char
   S6_ADDR[16];   /* IPV6 address */};


The UNIX domain corresponds to the following:

#define Unix_path_max    108struct sockaddr_un {     sa_family_t sun_family;               /* Af_unix */     char        Sun_path[unix_path_max];  /* pathname */};


3) Addrlen: corresponds to the length of the address.


Function execution successfully returns 0, failure returns-1.


Usually when the server is started with a well-known address (such as IP address + port number) to provide services, customers can use it to connect the server, and the client is not specified, the system is automatically assigned a port number and its own IP address combination. This is why the server usually calls bind () before listen, and the client does not invoke it, but instead generates one randomly from the system at Connect ().




2.3 Listen (), connect ()


As a server, after calling the socket (), bind (), it calls listen () to listen to the socket, and if the client calls connect () to make a connection request, the server will receive the request.

int listen (int sockfd, int backlog);

int connect (int sockfd, const struct SOCKADDR *addr, socklen_t Addrlen);

The first parameter of the Listen () function is the socket descriptor to listen on, and the second parameter is the maximum length of the corresponding socket listener queue. The socket created by the socket () function defaults to an active type, and the Listen () function turns the socket into a passive type, waiting for the client's connection request. The Listen () function creates a listening queue to hold the client connection to be processed, specifying the socket SOCKFD as the socket to be listened to, where the backlog generally has a value of 5.

The first parameter of the Connect () function is the client's socket descriptor, the second parameter is the server's socket address, and the third parameter is the length of the socket address. The client establishes a connection to the TCP server by calling the Connect () function, and if the connection succeeds, its first parameter, SOCKFD, uniquely identifies the connection. Function execution successfully returns 0, failure returns-1.




2.4 Accept ()


After the TCP server invokes the socket (), bind (), listen (), it listens for the specified socket address. The TCP client calls the socket (), connect () in turn, and then wants the TCP server to send a connection request. After the TCP server hears this request, it calls the Accept () function to take the receive request, so the connection is established. You can then start network I/O operations, which are similar to read/write I/O operations for normal files.

int accept (int sockfd, struct sockaddr *addr, socklen_t *addrlen);

The first parameter of the Accept () function is the server's socket descriptor, the second parameter is a pointer to the struct SOCKADDR *, which returns the client's protocol address, and the third parameter is the length of the protocol address. If Accpet succeeds, then its return value is a completely new description Word generated automatically by the kernel, representing the TCP connection to the returned client.

Note: The first parameter of the Accept () is the server's socket descriptor, which is generated by the server calling the socket () function, called the listener socket descriptor, and the Accept function returns the connected socket descriptor. A server typically simply creates a listener socket descriptor that persists throughout the life of the server. The kernel creates a connected socket descriptor for each client connection accepted by the server process, and when the server completes the service to a customer, the corresponding connected socket descriptor is closed.



2.5 read (), write ()


At this point the server and the customer have established a good connection. Network I/O can be called to read and write operations, that is, to achieve communication between different processes in the network. Network I/O operations have the following groups:

1) Read ()/write ()
2) recv ()/send ()
3) Readv ()/writev ()
4) recvmsg ()/sendmsg ()
5) Recvfrom ()/sendto ()




2.6 Close ()


After the server has established a connection with the client, some read and write operations are performed, and the corresponding socket descriptor is closed when the read and write operation is completed, like closing the open file by calling Fclose when the file is opened.

int close (int fd);

The default behavior of the close one TCP socket is to mark the socket as closed and then immediately return to the calling process. The descriptor can no longer be used by the calling process, which means that it can no longer be the first parameter of read or write.

Note: The close operation simply makes the reference count of the corresponding socket descriptor-1, which triggers the TCP client to send a terminating connection request to the server only if the reference count is 0.






3. C/S model


The c/S model (i.e. Client/server, client/server model) is The most classic server model, using a TCP connection, is shown in the model. TCP/IP protocol in the design and implementation does not differentiate between the client and the server, the communication both sides in fact the same status, but because a lot of data (such as news, music, video) are centrally provided by the company, such as when we watch the video, the server is responsible for providing relevant video resources, so the client and the service side of the point Many clients can access the server side to obtain resources.

TCP client and TCP server workflows that use the C/S model, as shown in:

The service-side workflow is as follows:

1) Call the socket function to create the socket (socket).

2) Call the BIND function to create the socket, assigning the IP address and port (BIND).

3) Call the Listen function to listen, waiting for the client to connect (listen).

4) Wait for the customer request arrives: When the request arrives, call the Accept function to accept the connection request, return a new socket corresponding to this connection, and prepare each other for communication (accept).

5) Call Write/read or SEND/RECV to read and write data, communicate through the socket returned by accept and the client.

6) Close the socket (close).



Customer end Workflow is as follows:

1) Call the socket function to create the socket (socket).

2) Call the Connect function to connect to the service side (connect).

3) Call Write/read or SEND/RECV to read and write data.

4) Close the socket (close).




4, TCP three-time handshake

The "three-time handshake" approximate process is as follows:

1) The client sends a SYN J to the server;
2) The server responds to the client with an ACK of J + 1 and sends a SYN K;
3) The client then sends a confirmation ACK k+1 to the server.

Such as:


As you can see, when the client calls connect, the connection request is triggered, the SYN J packet is sent to the server, then connect enters the blocking state, the server hears the connection request, receives the SYN J packet, calls the Accept function to receive the request to send SYN K to the client, ACK j+ 1, then accept into the blocking state, the client receives the server SYN K, after the ACK j+1, then connect returns, and the Syn K Confirmation, the server received an ACK k+1, accept return, this three times the handshake is completed, the connection is established.

Summary: The client's connect returns in the second time of the three handshake, while the server-side accept is returned for the third time in the three-time handshake.





5, TCP four wave


The four-time handshake in the socket releases the connection process, see:


An application process first calls close to actively close the connection, when TCP sends a fin m, and the other end receives Fin m, performs a passive shutdown to confirm the fin. Its reception is also passed as a file terminator to the application process, because the receive of fin means that the application process can no longer receive additional data on the corresponding connection; After a period of time, the application process that receives the file terminator calls close to close its socket. This causes its TCP to also send a fin N, which is acknowledged by the source sending TCP that receives the fin.





6. Moving Hands


Write a simple server, the client (using TCP)-the server has been listening to the local port No. 7777, if you receive a connection request, will receive the request and receive the message sent by the client, the client and the server to establish a connection and send a message.

Server:

#include <cstdio> #include <unistd.h> #include <stdlib.h> #include <cstring> #include < cassert> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa /inet.h>const int buffer_size = 4096;const int server_port = 7777;int Main () {int Server_socket;char buff[buffer_size]; int n;server_socket = socket (af_inet, sock_stream, 0); assert (Server_socket! =-1); struct sockaddr_in Server_addr;memset (&server_addr, 0, sizeof (SERVER_ADDR)); server_addr.sin_family = Af_inet;server_addr.sin_port = Htons (SERVER_PORT ); server_addr.sin_addr.s_addr = htonl (Inaddr_any); Assert (Bind (server_socket, (struct sockaddr *) &server_addr, sizeof (SERVER_ADDR))! =-1); Assert (Listen (Server_socket, 5)! = 1); struct sockaddr_in client_addr;socklen_t Client_ Addr_len = sizeof (CLIENT_ADDR), while (1) {printf ("waiting...\n"); int connfd = accept (server_socket, struct sockaddr*) &AMP;CLIENT_ADDR, &client_addr_len);p rintf ("here\n"); if (CONNFD = =-1) CONtinue;n = recv (CONNFD, Buff, buffer_size, 0); buff[n] = ' \ n ';p rintf ("Recv msg from client:%s\n", buff); close (CONNFD);} Close (server_socket); return 0;}

Client:

#include <cstdio> #include <unistd.h> #include <stdlib.h> #include <cstring> #include < cassert> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa /inet.h>const int buffer_size = 4096;const int server_port = 7777;int Main () {int client_socket;const char *server_ip = "127.0.0.1"; char buff[buffer_size] = "I ' m from client!\n"; client_socket = socket (af_inet, sock_stream, 0); Assert (client _socket! =-1); struct sockaddr_in server_addr;memset (&server_addr, 0, sizeof (SERVER_ADDR)); Server_addr.sin_ Family = Af_inet;server_addr.sin_port = Htons (server_port); server_addr.sin_addr.s_addr = inet_addr (server_ip); assert (Connect (client_socket, (struct sockaddr *) &server_addr, sizeof (SERVER_ADDR))! =-1); Assert (Send (Client_socket, Buff, strlen (buff), 0)! =-1); close (client_socket); return 0;}


"Socket Programming" chapter One

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.