Get ready, the system call accept () will be a bit weird! You can imagine what will happen: someone connects (connect ()) to your machine from far away through the port () you are listening to. Its connection will be added to the waiting queue (). You call accept () to tell it that you have an idle connection. It will return a new socket text descriptor! So you have two sockets. The old one is still listening to your port, and the new one is ready to send (send ()) and receive (recv ()) data. This is the process!
The function is defined as follows:
# include & ltsys/socket . h & gt;
int accept(int sockfd,void *addr,int * addrlen);
Sockfd is very simple, it is the same socket descriptor as in listen (). Addr is a pointer to the local data structure sockaddr_in. This is the destination of the information you need to access (you can decide which address to call you at which port). Before its address is passed to accept, addrlen is a local integer variable set to sizeof(struct sockaddr_in). Accepting will not give addr extra bytes. If you put less, then it will change.
Change the value of addrlen.
Similarly,-1 is returned when an error occurs, and the global error variable errno is set.
Now is the code snippet that you should be familiar with.
# include & ltstring.h & gt
# include & ltsys/socket . h & gt;
# include & ltsys/types . h & gt;
# define MYPORT 3490 /* user access port */
#define BACKLOG 10 /* How much to wait for connection control */
Master ()
{
Int sockfd, new_fd/* Listen for new connections on sock_fd, new _ fd */
Struct sockaddr _ in my _ addr/* address information */
Struct sockaddr _ in their _ addr/* Address information of connector */
int sin _ size
sockfd = socket(AF_INET,SOCK_STREAM,0); /* Error checking */
My _ address. sin _ home = AF _ INET/* host byte order */
my _ addr . sin _ port = htons(my port); /* Short, network byte order */
my _ addr . sin _ addr . s _ addr = in addr _ ANY; /* Automatically populate my IP */
bzero(& amp; (my_addr.sin_zero),; /* Zeroing the rest of the structure */
/* Don't forget to check these calls for errors: */
bind(sockfd,(struct sockaddr *)& amp; my_addr,sizeof(struct sockaddr));
Listen (sockfd, backlog);
sin _ size = sizeof(struct sockaddr _ in);
Accept (sockfd &; Their addresses. sin _ size);
.
.
.
Note that you should use the new socket descriptor new_fd in the system calls send () and recv (). If you only want one connection to enter, you can use close () to close the original file descriptor sockfd to avoid more connections on the same port.