Free for PREMIUM members
Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium
/* Some preliminaries: */
int sockfd, newsockfd; /* fds for socket(), accept() */
struct sockaddr_in serv_addr, cli_addr; /* sockaddr_in from <netinet/in.h> */
long clilen; /* in linux 'int'! */
/* socket() :
"The socket subroutine creates a socket in the specified AddressFamily and of the specified type.
The socket subroutine returns a descriptor (an integer) that can be used in later subroutines
that operate on sockets." */
sockfd = socket(AF_INET, SOCK_STREAM, 0); /* Address family, type, protocol */
/* bind() :
"The bind subroutine assigns a Name parameter to an unnamed socket.
Sockets created by the socket subroutine are unnamed;
they are identified only by their address family.
Subroutines that connect sockets either assign names or use unnamed sockets."
struct sockaddr comes from <sys/socket.h> */
bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
/* listen() :
"The listen subroutine performs the following activities:
- Identifies the socket that receives the connections.
- Marks the socket as accepting connections.
- Limits the number of outstanding connection requests in the system queue." */
listen(sockfd, 5); /* 5 = Queue depth! */
/* accept() :
"The accept subroutine extracts the first connection on the queue of pending connections, creates a new socket with the same properties as the specified socket, and allocates a new file descriptor for that socket
The accepted socket cannot accept more connections.
The original socket remains open and can accept more connections"
==> This is what gheist said:
The number of accepted sockets is limited only by your program or system resources. <== */
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
/* Now do whatever you want with the accepted socket */
read(newsockfd, buffer, 255);
write(newsockfd, "Message xxxxxxxx", 17);
/* close the accepted socket */
/* At the very end, close the original (listening) socket) */
Open in new window
We value your feedback.
Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!
Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.