[Linux] system programming-8-socket

Li Zhuming 2021-01-21 19:24:52
linux programming-8-socket programming socket



Preface

original text :https://www.cnblogs.com/lizhuming/p/14309823.html

11. Socket

  • The pipes described above 、 Semaphore 、 Message queuing, shared memory and so on are all used for Single computer Communication between processes
  • Socket based interprocess communication mechanism , Can be realized Cross host Communication between processes

11.1 Socket brief introduction

  • Socket (socket) It's a communication mechanism , With this mechanism , client <-> The server The communication mode of the model can be carried out on the local device , It can also be done across the network .
  • Socket mechanism can implement Multiple clients to one server .
  • stay Socket in , It uses a socket to record a connection to the network , The socket is an integer .
  • In the network , It can be done to socket Make a network connection 、 Reading data 、 Send data and terminate the connection .
  • Related header file
#include <sys/types.h>
#include <sys/socket.h>
  • Socket itself is only the hub of user program and kernel interaction information , No network protocol address, port number, etc , So we need to use bind() Bind it
  • Conceptually note the difference between socket and port number . Socket can be understood as IP+ Port number .
  • Personal understanding : A port number corresponds to an application , Within an application , In theory, multiple sockets can be bound to a single port number , But most systems don't allow that . Navel
  • A server usually creates only one Listening socket , It exists throughout the life of the server . meanwhile , The server also creates one for each connected client Socket connected stay accept() After successful connection , The kernel will automatically generate a new socket ).

11.2 socket()

  • socket() Function to create a socket The descriptor , Used to identify the only one socket.
  • The function prototype :int socket(int domain, int type, int protocol);
    • domain: Represents the protocol family used by the socket ( about TCP/IP, General choice AF_INET That's all right.
      • AF_UNIX, AF_LOCAL: Local communication
      • AF_INET : IPv4
      • AF_INET6 : IPv6
      • AF_IPX : IPX - Novell agreement
      • AF_NETLINK : Kernel user interface device
      • AF_X25 : ITU-T X.25 / ISO-8208 agreement
      • AF_AX25 : Amateur radio AX.25 agreement
      • AF_ATMPVC : Visit original ATM PVC
      • AF_APPLETALK : AppleTalk
      • AF_PACKET : The underlying packet interface
      • AF_ALG : Kernel encryption API Of AF_ALG Interface
    • type: Service type
      • SOCK_STREAM: Provide reliable ( That is to ensure that the data is correctly transmitted to the other party ) Connection oriented Socket service , More for data ( Such as file ) transmission , Such as TCP agreement .
      • SOCK_DGRAM: It's about providing unprotected message oriented Socket service , It is mainly used to send broadcast information on the network , Such as UDP agreement , Provide connectionless and unreliable datagram delivery service .
      • SOCK_SEQPACKET: To provide ordered... For fixed maximum length datagrams , reliable , Data transmission path based on bidirectional connection .
      • SOCK_RAW: Represents the original socket , It allows applications to access raw packets at the network layer , This socket is less used , It can be ignored for the time being .
      • SOCK_RDM: Provides a reliable datagram layer that does not guarantee sorting .
    • protocol: The protocol used by the socket . When protocol by 0 when , Will automatically select type Default protocol corresponding to type .
      • Such as : When in IPv4, Only TCP Provided by agreement SOCK_STREAM This reliable service , here ,protocol by 0 that will do .
    • return
      • success : Return a greater than 0 Socket descriptor for
      • Failure : return -1

11.3 bind()

  • bind() Function is used to put a IP The address or port number is bound to a socket , Many times, the kernel will help us automatically bind a IP Address and port number , But you can also manually bind .
  • The function prototype :int bind(int sockfd, struct sockaddr *my_addr, socklen_t addrlen);
    • sockfd:sockfd By socket() Socket descriptor returned by function .
    • my_addr:my_addr Is a pointer to the socket address structure .
    • addrlen:addrlen Designated by addr The byte length of the address structure pointed to .
    • return :
      • success : return 0
      • Failure : return -1
  • sockaddr Structure :
struct sockaddr {
sa_family_t sa_family;
char sa_data[14]; // fill IP、 Port number and other information
};
  • Generally not used sockaddr Structure , Because the operation is not convenient , But use sockaddr_in. Because they take up the same space . Can replace .( When you assign a parameter, you can cast the type )
  • sockaddr_in Structure :
struct sockaddr_in {
short int sin_family; /* Protocol family */
unsigned short int sin_port; /* Port number */
struct in_addr sin_addr; /* IP Address */
unsigned char sin_zero[8]; /* sin_zero It's to make sockaddr And sockaddr_in Two data structures keep the same size but keep empty bytes */
};

11.4 connect()

  • connect() Function for the client , take socket With the remote IP Address 、 Port number binding . If in TCP The function is called in the client , There will be a handshake process .
  • The function prototype :int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
    • Parameter reference bind() function
    • return :
      • success : return 0
      • Failure : return -1, Mistakes exist in error in

11.5 listen()

  • listen() Function is used on the server side , Put the server into listening state , Waiting for the client to request a connection .
  • The function prototype :int listen(int sockfd, int backlog);
    • sockfd:sockfd It's the socket descriptor .
    • backlog: Express sockfd The maximum value that the waiting connection queue can reach .
      • When multiple clients try to connect to the server at the same time , The kernel maintains a queue in its own process space to hold these requests , When the queue is full , The request coming in from behind , The server will discard it , The client will receive a connection failure error .

11.6 accept()

  • accept() Function is used on the server side , It mainly deals with connection requests from clients .
  • The function prototype :int accept(int s, struct sockaddr *addr, socklen_t *addrlen);
    • Parameter reference bind() function
    • return :
      • success : If the connection is successful , We'll create a and parameter sockfd Connection sockets with the same properties , And assign a file descriptor to the connection socket . Finally return to a socket The descriptor ( Nonnegative value ).
      • Failure : return -1
  • When the socket is marked as blocking mode , When there are no outstanding connection requests in the queue , call accept() Function will always block , Until a connection is established with the remote end .
  • When the socket is marked as non blocking , When there are no outstanding connection requests in the queue , call accept() The function immediately returns EAGAIN.

11.7 read()

  • When the client and server are established TCP After the connection , We can go through sockfd socket descriptor ( Connected socket descriptor , from sccept() produce ) To send and receive data .
  • Receiving data from the network can use read()、recv()、recvfrom() etc. .
  • The function prototype :ssize_t read(int fd, void *buf, size_t count);
    • fd: It could be a file descriptor , It can also be a socket descriptor . In this section, the socket descriptor .
    • buf: Buffer to receive data .
    • count: The number of bytes to read .
    • return :
      • success : The number of bytes actually read .( Situation 1 : The number of bytes remaining in the file is less than count, The number of bytes returned is less than count Of )
      • Failure : return -1, Mistakes exist in error in :
        • EINTR: Interrupted by a signal before reading data .
        • EAGAIN: Use O_NONBLOCK Flag specifies the nonblocking I / O , But currently there is no data to read .
        • EIO: I / O error , It may be that the process in the background process group is trying to read its control terminal , But the read operation is invalid , Or be signaled SIGTTIN Blocked , Or its process group is an orphan process group , It is also possible to perform low-level I / O errors such as reading disks or tape drives .
        • EISDIR:fd Point to a directory .
        • EBADF:fd Not a valid socket descriptor , Or not open for read operations .
        • EINVAL:fd The connected object is unreadable .
        • EFAULT:buf Out of user accessible address space .

11.8 recv()

  • recv() Function function and read() The function functions are similar , Both client and server can use this function to receive data from the other end .
  • recv() It's actually copying data , Receiving data is done by protocol .recv() Function checks the receive buffer of the socket first , If there is no data in the buffer or data is being received ,recv() The function will wait , Until the protocol receives data ,recv() To read the data in the buffer .
  • The function prototype :ssize_t recv(int sockfd, void *buf, size_t len, int flags);
    • sockfd: Specifies the receiver socket descriptor .
    • buf: Specify a buffer to receive data , This buffer is used to hold recv() Data received by function .
    • len: Appoint recv() The length of the data copied by the function .
    • flags
      • 0: It's usually set to 0 that will do
      • MSG_OOB: Receive to out-of-band The data sent out .
      • MSG_PEEK: Keep the original data , That is to say, the received data will not be deleted in the buffer , If you call recv() Function will also copy the same data to buf in .
      • MSG_WAITALL: Force to receive the specified len The size of the data can be returned , Unless there's an error or a signal .
      • MSG_NOSIGNAL:recv() Functions are not SIGPIPE Signal interruption .
    • return :
      • success : The number of bytes actually read .
      • Failure : return -1, Mistakes exist in error in :
        • EBADF:fd Not a valid socket descriptor , Or not open for read operations .
        • EFAULT:buf Out of user accessible address space .
        • ENOTSOCK: Parameters s A description word for a document , Not socket.
        • EINTR: Interrupted by a signal before reading data .
        • EAGAIN: This action blocks the process , But parameters s Of socket Not to be blocked .
        • ENOBUFS:buf Out of memory .
        • ENOMEM: Out of memory .
        • EINVAL: Incorrect parameter passed in .

11.9 write()

  • write() Functions are generally used to be stable TCP Transferring data in a connection .UDP Protocols can also be used .
  • write() The function is not sent immediately after writing data , When to send it is up to TCP/IP The stack decides .
  • The function prototype :ssize_t write(int fd, void *buf, size_t count);
    • fd: It could be a file descriptor , It can also be a socket descriptor . In this section, the socket descriptor .
    • buf: Buffer to send data .
    • count: Need to send bytes .
    • return :
      • success : Returns the number of bytes actually written
      • Failure : return -1, Mistakes exist in error in
  • Be careful , Network programming write() I'm not responsible for writing all the data and then returning it , Maybe I came back on the way . If you want to ensure that all data is written , It has to cycle write() function , It can be self-contained . The code is as follows :(copy Wildfire
/* Write "n" bytes to a descriptor. */
ssize_t writen(int fd, const void *vptr, size_t n)
{
size_t nleft; // The number of bytes left to write
ssize_t nwritten; // The number of bytes that have been written
const char *ptr; //write The buffer
ptr = vptr; // Let's bring in the write A backup copy of the buffer to be written
nleft = n; // The remaining number of bytes to write is initialized to the total number of bytes to write
// Check the validity of the number of bytes to be written in the parameter
while (nleft > 0) {
if ( (nwritten = write(fd, ptr, nleft)) <= 0) { // hold ptr write in fd
if (nwritten < 0 && errno == EINTR) // When write Return value less than 0 And because it was interrupted by a signal
nwritten = 0; /* and call write() again */
else
return(-1); /* error Others are less than 0 The situation is wrong */
}
nleft -= nwritten; // There are still bytes left to write = There are still bytes left to write - The number of bytes that have been written this time
ptr += nwritten; // The next buffer position to start writing = The current position of the buffer is shifted to the right by the number of bytes that have been written
}
return(n); // Returns the number of bytes that have been written
}

11.10 send()

  • Both client and server applications can use write() Function to TCP The other end of the connection sends data .
  • When using send() When sending data ,send() We will first compare the length to be sent len And sockets sockfd Send buffer length of , if len Big , Then return to SOCKET_ERROR. if len Less than or equal to ,send() Function first checks if the protocol is sending the socket sockfd The data in the send buffer , If it is , Just wait for the transmission to complete , If it hasn't started yet , be send() Function will continue to compare len And the length of the remaining space in the transmit buffer , if len Big , Wait for the send buffer to be sent , if len Less than or equal to , Then we put the data copy To the send buffer .
  • copy After success ,send() The function immediately returns , But it doesn't have to be sent right away , When to send depends on TCP/IP agreement .
  • The function prototype :int send(int sockfd, const void *msg, size_t len, int flags);
    • sockfd: Specifies the sender socket descriptor .
    • msg: Specify the buffer to send data .
    • len: Appoint recv() The length of the data copied by the function .
    • flags: It's usually 0 that will do .
    • return :
      • success : Go back to the actual copy Bytes of
      • Failure : return SOCKET_ERROR

11.11 sendto()

  • sendto() Function and send() Function similarity , But it will go through struct sockaddr Point to the to Structure specifies which remote host to send to , stay to The remote host's IP Address 、 Port number, etc , and tolen The parameter is to specify to The byte length of the structure .
  • sendto() It is suitable for the connected datagram or streaming socket to send data .
  • The function prototype :int sendto(int s, const void *msg, size_t len, int flags, const struct sockaddr *to, socklen_t tolen);
    • s: A description word that identifies the socket interface .
    • buf: Buffer containing data to be sent .
    • len:buf The length of data in the buffer .
    • flags: Call mode flag bit .
    • to:( Optional ) The pointer , The address of the destination socket .
    • tolen:to The length of the address in question .

11.12 close()

  • close() Function is used to close a specified socket .
  • The function prototype :int close(int fd);

11.13 ioctlsocket()

  • ioctlsocket() Function is used to get operation parameters related to setting socket .
  • The function prototype int ioctlsocket( int s, long cmd, u_long *argp);
    • s: Specifies the socket descriptor to operate on .
    • cmd: To socket s Operation command of .
      • FIONBIO: Allows or disallows sockets s Non blocking mode of .
      • FIONREAD: Determine the socket s The amount of data automatically read in .argp Points to an unsigned long integer , There are ioctlsocket() The return value of .
      • SIOCATMARK: Is it true that all out of band data has been read in .
    • argp: Point to cmd A pointer to the parameter of the command .argp Points to an unsigned long integer . If nonblocking mode is allowed, it is nonzero , If non blocking mode is prohibited, it is zero .
    • return :
      • success :ioctlsocket() return 0.
      • Failure : return SOCKET_ERROR error , Applications can be accessed through WSAGetLastError() Get the corresponding error code :
        • WSANOTINITIALISED: In the use of this API You should first successfully call WSAStartup().
        • WSAENETDOWN:WINDOWS Socket implementation detects network subsystem failure .
        • WSAEINVAL:cmd For illegal orders , perhaps argp The parameter in question does not apply to this cmd command , Or the command does not apply to this type of socket .
        • WSAEINPROGRESS: A blocked WINDOWS The socket call is running .
        • WSAENOTSOCK: The descriptor is not a socket .

11.14 getsockopt()、setsockopt()

  • getsockopt()、setsockopt() Get and set socket respectively .
  • The function prototype :
    • int getsockopt(int sockfd, int level, int optname, void *optval, socklen_t *optlen);
    • int setsockopt(int sockfd, int level, int optname,const void *optval, socklen_t optlen);
      • sockfd: Specifies the socket descriptor to operate on .
      • level
        • SOL_SOCKET: It means that Socket layer .
        • IPPROTO_TCP: It means that TCP layer .
        • IPPROTO_IP: It means that IP layer .
      • optname: Specific options for this layer , Such as :
        • about SOL_SOCKET Options
          • SO_REUSEADDR( Allows reuse of local addresses and ports )
          • SO_SNDTIMEO( Set the send data timeout )
          • SO_SNDTIMEO( Set the receive data timeout )
          • SO_RCVBUF( Set the send data buffer size ) wait .
        • about IPPROTO_TCP Options
          • TCP_NODELAY( Don't use Nagle Algorithm )
          • TCP_KEEPALIVE( Set up TCP Time to live ) wait .
        • about IPPROTO_IP Options
          • IP_TTL( Set the lifetime )
          • IP_TOS( Set service type ) wait .

Reference resources :

* Wildfire 
版权声明
本文为[Li Zhuming]所创,转载请带上原文链接,感谢
https://javamana.com/2021/01/20210121192351529v.html

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云