accept())Welcome to a comprehensive guide on C Programming! In this lesson, we'll delve into the accept() function, which is crucial for establishing connections in a server-client setup.
Before we dive in, let's ensure you have the prerequisites down:
accept()The accept() function is used by a server to accept connections from clients. It waits for a connection request from a client, and when it receives one, it creates a new socket that represents the connection.
š” Pro Tip: accept() is a built-in function in C sockets library.
int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen)
sockfd: The socket that the server is listening onaddr: The address of the client requesting a connectionaddrlen: The length of the socket addressLet's create a simple server that listens for incoming connections.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define PORT 8080
int main() {
int server_fd, client_fd;
struct sockaddr_in server_addr, client_addr;
server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
server_addr.sin_addr.s_addr = INADDR_ANY;
if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
if (listen(server_fd, 3) < 0) {
perror("listen");
exit(EXIT_FAILURE);
}
printf("Server is running on port %d\n", PORT);
int addr_len = sizeof(client_addr);
client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &addr_len);
if (client_fd < 0) {
perror("accept");
exit(EXIT_FAILURE);
}
// Now we can handle the client here.
return 0;
}Now let's create a client to connect to our server.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define PORT 8080
int main() {
int sockfd, connfd;
struct sockaddr_in server_addr;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
if (inet_pton(AF_INET, "127.0.0.1", &server_addr.sin_addr) <= 0) {
perror("inet_pton failed");
exit(EXIT_FAILURE);
}
connfd = connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr));
if (connfd < 0) {
perror("connect failed");
exit(EXIT_FAILURE);
}
// Now we have connected to the server.
return 0;
}Which function does the server use to accept incoming connections?
Stay tuned for more on C Programming, and remember to practice regularly to master these concepts! šÆ