socket network programming basics

1. Socket programming function 1. Socket
function
Prototype: int socket(int domain, int type, int protocol);

Role: Create an endpoint and return a socket descriptor.

Parameter resolution:
domain: Specify a session domain name and select a protocol family for this session. Included in <sys/socket.h>. The current default format includes
    AF_UNIX,AF_LOCAL AF_INET AF_INET6...
type: The type description of the new socket.
    SOCK_STREAM SOCK_DGRAM SOCK_SEQQPACKET...
protocol: The domain and type have basically determined what type of socket the newly created socket is. In the last step, the protocol is used to determine which protocol (TCP?UDP?) the socket supports.
    If it is 0, it can be understood as a wildcard or a default value, that is, I do not specify a protocol, and the kernel itself decides which protocol to use.

Return value: success returns socket description, failure returns -1. 2. bind

function
Prototype: int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen);

Function: When a descriptor is created through socket, it exists a namespace, but no address space has been assigned to it. The bind function is to assign the addr address to sockfd.

Parameter resolution:
sockfd: Socket descriptor for unallocated address space.
addr: address pointer.
      Assignment:
        sockaddr_in addr;

    
    memset(&addr, 0, sizeof(addr));

        addr.sin_family = AF_INET;

        addr.sin_port = htons(m_nPort);

        addr.sin_addr.s_addr = INADDR_ANY;
    INADDR_ANY: indicates when the host has multiple ips , the client can connect to any ip.
addrlen: address length.

Return value: 0 for success, -1 for failure.

3.listen function
Prototype: int listen(int sockfd, int backlog);

Function: Handle the client's three-way handshake process.

Parameter resolution:
sockfd: The socket descriptor of the allocated address space.
backlog: The backlog parameter determines the maximum value of the sum of the number of connections in the outstanding queue and the completed queue.
    The kernel maintains two queues for any given listening socket.
    1) The outstanding connection queue
      is sent by the client and arrives at the server, while the server is waiting to complete the corresponding TCP three-way handshake process.
      These sockets are in SYN_RCVD state.    
    2) Completed connection queue
      Each client that has completed the TCP three-way handshake process corresponds to one of them. These sockets are in the ESTABLISHED state.
    
Return value: 0 for success, -1 for failure.

4.Accept function
Prototype: int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);

Function: Get a fd and address information from the completed connection queue of bind . If the queue is empty, the process goes to sleep (the socket is blocking).

Parameter resolution:
sockfd: The socket descriptor of the allocated address space.
addr: Save the address information received from the customer.
addrlen: Customer address length.

Return value: Returns the client connection socket descriptor on success, -1 on failure.

Listen and accept process reference documents:
http://blog.csdn.net/ordeder/article/details/21551567

5.connect function
prototype: int connet(int sockfd, const struct sockaddr *servaddr, socklen_t addrlen);

role: used for A TCP client to establish a connection with the server.
    The client does not have to call the bind function before calling connect, because the kernel will select an ephemeral port as the source port based on the source IP address.
    In the case of a TCP socket, calling the connect function will trigger the TCP three-way handshake process and return only when the connection is established successfully or in error.

Parameter parsing:
sockfd: The socket descriptor for the allocated address space.
servaddr: Pointer to a socket address structure containing the server IP and port number.
addrlen: The size of the socket address structure.

Return value: 0 is returned on success, -1 on error. If it fails, the socket needs to be recreated.

6.recv function
Prototype: ssize_t recv(int sockfd, void *buf, size_t len, int flags);

Function: Copy the contents of the sockfd receiving buffer to buf.
    The recv function just copies the data, the real received data is done by the protocol.

Parameter analysis:
sockfd: The socket descriptor for the allocated address space.
buf: save the received data.
len: Copy the data length from the sockfd kernel receive buffer.
flags: generally fill in 0 to set the mode.

Return value: greater than 0 means the received data byte length, 0 means the other party disconnects, -1 means failure.

7.send function
Prototype: ssize_t send(int sockfd, const void *buf, size_t len, int flags);

Role: Copy the contents of buf to the sockfd kernel send buffer.
    The send function is just to copy the data, the real sending data is done by the protocol.

Parameter analysis:
sockfd: The socket descriptor of the allocated address space.
buf: save send data.
len: The length of copying buf data to the sockfd kernel send buffer.
flags: generally fill in 0 to set the mode.

Return value: Returns the length of bytes sent. -1 means failure.

Send and recv function processing process reference documents:
http://www.cnblogs.com/jianqiang2010/archive/2010/08/20/1804598.html

8. setsockopt function 9.

getsockopt function

10. Other functions
inet_pton, inet_ntop, getsockname, getpeername


2. Question
1. The difference between socket blocking and non-blocking (column full)
  blocking: When a socket call that cannot be completed immediately is issued, its process goes to sleep, waiting for the corresponding operation to complete.
  Socket blocking is divided into the following 4 categories:
  1) Input operations: read, readv, recv, recvfrom, recvmsg
    For blocked TCP sockets, if there is no data to read in the socket's receive buffer, the process will be put to sleep , until data arrives.
    For non-blocking sockets, if there is no data to read in the receive buffer, the corresponding call will immediately return an EWOULDBLOCK error.
  2) Output operation: write, writev, send, sendto, sendmsg
    The kernel will copy from the buffer of the application process to the send buffer of the socket.
    For blocking sockets, if there is no room in its socket send buffer, the process will be put to sleep until there is room.
    For non-blocking TCP sockets, the output function call will immediately return an EWOULDBLOCK error if there is no room at all in its send buffer. If there is some room in the send buffer, the
    return value will be the number of bytes the kernel was able to copy into that buffer.
  3) Receive incoming connections: accept
    calls the accept function for blocking sockets. When no new connections arrive, the calling process will be put to sleep.
    For non-blocking sockets calling the accept function, when no new connections arrive, the accept call will return an EWOULDBLOCK error immediately.
  4) Initiate an outgoing connection: connect
    For a blocking socket, if it cannot be connected, it will block (Linux blocks for 75s). If you want not to block, you can use the timer signal mechanism to handle it.
    For non-blocking sockets, if the connection fails, it will return immediately. If it is 0, it means that the connection has been established; if it is -1, if the error is EINPROGRESS, use the select function to monitor the connection status of fd.

  fcntl function settings.

Reference document:
http://blog.csdn.net/pingnanlee/article/details/7770087
http://blog.csdn.net/nphyez/article/details/10268723

2. When gdb debugs the coredump file, the function name is ?? ?? Question mark
  Some libraries cannot be found (/lib/libstdc++.so.6), or the versions do not match.

3. The difference between sleep and blocking waiting

4. Detailed processing of the epoll model

5. Detailed explanation of nginx

6. The process of shaking hands three times and waving four times.
  Three-way handshake:
    1) The client sends a SYN packet to the server, and enters the SYN_SEND state, waiting for the server to confirm.
    2) The server receives the SYN packet and confirms it. At the same time, it sends a SYN packet, and ACK+SYN, and the server enters the SYN_RECV state.
    3) The client receives the SYN+ACK packet from the server, and sends the confirmation packet ACK (ACK=k+1) to the server. After the packet is sent, the client and the server enter the ESTABLISHED state and complete the three-way handshake.
    After completing the three-way handshake, the client and server begin to transmit data.

  Four waves of hands:
    TCP is a full-duplex communication method.
    1) The end that initiates the closing sends a FIN to tell the closed end that I will close the sending link and will no longer send data to you, but you can send data to me.
    2) The passively closed end sends ACK to confirm.
    3) The passive closing end sends a FIN, telling the closing end that I will close my sending link and will no longer send data to you.
    4) The end that initiates the shutdown sends an ACK.


7. TIME_WAIT and CLOSE_WAIT state
 CLOSE_WAIT:
  When closing the TCP connection, the party that
  initiates the closing of the TCP connection is called client, and the party that passively closes is called server. After a passively closed server receives a FIN, but does not send an ACK, the TCP state is CLOSE_WAIT.
 TIME_WAIT:
  According to the three-way handshake disconnection defined by the TCP protocol, the socket of the party that initiates the active closure of the socket will enter the TIME_WAIT state.
  The TIME_WAIT state will last for 2 MSL (Max Segment Lifetime), which defaults to 4 minutes under Windows, or 240 seconds.
  The socket in the TIME_WAIT state cannot be recycled. The specific phenomenon is that for a server that handles a large number of short connections,
  if the server actively closes the client's connection, there will be a large number of sockets in the TIME_WAIT state on the server side,
  even more than in the Established state. There are too many sockets, which seriously affects the processing capacity of the server, and even exhausts the available sockets and stops the service.

  The problem of the TIME_WAIT state can be solved by setting the port multiplexing or modifying the TIME_WAIT waiting time.
 
Reference document:
http://www.cnblogs.com/sunxucool/p/3449068.html
http://www.cnblogs.com/Jessy/p/3535612.html

8. The meaning of TIME_WAIT status setting

9. How SO_REUSEADDR solves TIME_WAIT The problem of port multiplexing in the state?
  The socket with the SO_REUSEADDR flag set, when binding the port, if the port is not in use or is in use but in the TIME_WAIT state, the binding can be successful.
  Binding fails if in use in a non-TIME_WAIT state.

Reference document:
http://www.cnblogs.com/qq78292959/archive/2013/01/18/2865926.html



9. How does TCP/IP ensure the accuracy and sequence of data


10. Thread synchronization (Linux)
  1) Mutex

  2) Semaphore

  3) Condition variable
    

11. Interprocess communication socket



error code table:
http://blog.chinaunix.net/uid-116213-id-3376727.htmlNetwork

Programming:
http://blog.csdn.net/weiyuefei/article/category/2821641
http://blog.csdn.net/weiyuefei/article/details/52242778


Review section:
1.C/C++ basic syntax
2.TCP/ IP protocol
3. socket programming
4. Thread and process synchronization and asynchrony and how to program
5. Server concurrent processing (epoll)
6. Which open source libraries
  are used jsoncpp, tinyxml, openssl, mongodb





Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325763246&siteId=291194637