- 1 year ago
Expected 'select' behavior while using a socket without connection attempts
Comment
1 / 1
If you are trying to use a socket without establishing a connection first, then you should expect the select
call to return an error. This is because the select
function expects that you have already established a connection with the socket before calling it.
To use select
with a socket, you need to first create a socket object and then use it to establish a connection with another socket. Once the connection is established, you can use select
to wait for incoming data on the socket.
Here is an example of how to use select
with a socket:
c#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#define MAX_LINE 256
int main(int argc, char *argv[]) {
struct sockaddr_in sin;
fd_set read_set, ready_set;
char buf[MAX_LINE];
int max_fd, len, sock, port;
if (argc != 2) {
fprintf(stderr, "usage: %s <port>\n", argv[0]);
exit(1);
}
port = atoi(argv[1]);
/* Create socket */
if ((sock = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
perror("socket error");
exit(1);
}
/* Configure socket */
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = INADDR_ANY;
sin.sin_port = htons(port);
/* Bind socket to port */
if (bind(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
perror("bind error");
exit(1);
}
/* Listen on socket */
if (listen(sock, 5) < 0) {
perror("listen error");
exit(1);
}
/* Initialize read set */
FD_ZERO(&read_set);
FD_SET(sock, &read_set);
max_fd = sock;
/* Wait for connections */
while (1) {
ready_set = read_set;
if (select(max_fd+1, &ready_set, NULL, NULL, NULL) < 0) {
perror("select error");
exit(1);
}
/* Check for new connection */
if (FD_ISSET(sock, &ready_set)) {
int new_sock;
struct sockaddr_in client_addr;
len = sizeof(client_addr);
new_sock = accept(sock, (struct sockaddr *)&client_addr, &len);
if (new_sock < 0) {
perror("accept error");
}
else {
printf("Connection from %s\n", inet_ntoa(client_addr.sin_addr));
FD_SET(new_sock, &read_set);
max_fd = (new_sock > max_fd ? new_sock : max_fd);
}
}
/* Check for incoming data */
for (int i = sock+1; i <= max_fd; i++) {
if (FD_ISSET(i, &ready_set)) {
if ((len = read(i, buf, sizeof(buf))) == 0) {
printf("Connection closed\n");
close(i);
FD_CLR(i, &read_set);
}
else {
buf[len] = '\0';
printf("%s", buf);
}
}
}
}
return 0;
}
This example sets up a socket to listen for incoming connections on a specified port. It uses select
to wait for incoming data on the socket and to check for new connections. When data is