/* select2.c: test time out using fd_set variable */ #include #include #include #include #include #include #include #include #define MAXSIZE 100 main(int argc, char *argv[]) { int s; /* s = socket */ struct sockaddr_in in_addr; /* Structure used for bind() */ struct sockaddr_in sock_addr; /* Output structure from getsockname */ struct sockaddr_in src_addr; /* Used to receive (addr,port) of sender */ int src_addr_len; /* Length of src_addr */ int len; /* Length of result from getsockname */ char line[MAXSIZE]; if (argc == 1) { printf("Usage: %s port\n", argv[0]); exit(1); } /* --- Create a socket --- */ s = socket(AF_INET, SOCK_DGRAM, 0); /* --- Set up socket end-point info for binding --- */ in_addr.sin_family = AF_INET; /* Protocol family */ in_addr.sin_addr.s_addr = htonl(INADDR_ANY); /* Wildcard IP address */ in_addr.sin_port = htons(atoi(argv[1])); /* Use any UDP port */ /* --- Here goes the binding... --- */ if (bind(s, (struct sockaddr *)&in_addr, sizeof(in_addr)) == -1) { perror("bind: "); printf("- Note: this program can be run on any machine...\n"); printf(" but you have to pick an unsed port#\n"); exit(1); } else { printf("OK: bind SUCCESS\n"); } fd_set recv_fds; /* Recv file descriptors used by select */ struct timeval timeout; /* Time value for time out */ FD_ZERO( &recv_fds ); // recv_fds = 00...0 FD_SET( s, &recv_fds ); // Set bit s in recv_fds timeout.tv_sec = 5; /* Timeout = 5 sec + 0 micro sec*/ timeout.tv_usec = 0; int result ; printf("Now use udp4-s3 and send a UDP message to port %s before %d sec !!!....\n", argv[1], timeout.tv_sec ); result = select(FD_SETSIZE, &recv_fds, NULL, NULL, &timeout); printf("select( ) returns: %d\n", result); }