The system calls accept (), which is a bit odd! As you can imagine, someone connects (connect () to your machine from a long distance through a port you are listening on (listen. Its connection will be added to the queue waiting for acceptance (accept. You call accept () to tell it that you have idle connections. It will return a new socket file descriptor! In this way, you have two sockets. The original one is listening to your port, and the new one is preparing to send () and receive (recv () data. This is the process of the Linux Accept function!
The Linux Accept function is defined as follows:
# Include <sys/socket. h>
Intaccept (intsockfd, void * addr, int * addrlen );
Sockfd is quite simple. It is the same socket descriptor as listen. Addr is a pointer to the local data structure sockaddr_in. This is where the access information is required. You can determine the address that calls you on that port ). Before its address is passed to accept, addrlen is a local integer variable and is set to sizeof (structsockaddr_in ). Accept will not give additional bytes to addr. If you put less, it will be reflected by changing the value of addrlen. Similarly, if an error occurs,-1 is returned and the global error variable errno is set.
This is a code snippet you should be familiar.
- # Include <string. h>
- # Include <sys/socket. h>
- # Include <sys/types. h>
- # DefineMYPORT3490/* User Access Port */
- # DefineBACKLOG10/* Number of pending connections */
- Main ()
- {
- Intsockfd, new_fd;/* listenonsock_fd, newconnectionnew_fd */
- Structsockaddr_inmy_addr;/* address information */
- Structsockaddr_intheir_addr;/* connector 'saddressinformation */
- Intsin_size;
- Sockfd = socket (AF_INET, SOCK_STREAM, 0);/* error check */
- My_addr.sin_family = AF_INET;/* hostbyteorder */
- My_addr.sin_port = htons (MYPORT);/* short, networkbyteorder */
- My_addr.sin_addr.s_addr = INADDR_ANY;/* auto-fillwithmyIP */
- Bzero (& (my_addr.sin_zero),;/* zerotherestofthestruct */
- /* Don 'tforgetyourerrorcheckingforthesecils :*/
- Bind (sockfd, (structsockaddr *) & my_addr, sizeof (structsockaddr ));
- Listen (sockfd, BACKLOG );
- Sin_size = sizeof (structsockaddr_in );
- New_fd = accept (sockfd, & their_addr, & sin_size );
- .
- .
- .
Note: The new socket descriptor new_fd should be used in system call send () and recv. If you only want a connection, you can use close () to close the original file descriptor sockfd to avoid more connections on the same port.