/* poll1.c: use poll to perform time out for 1 socket */ #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"); } /* ============================================== Set up poll structur ============================================== */ struct pollfd fds[1]; // 1 socket int timeout = 5000; // 5000 msec = 5 sec fds[0].fd = s; // Test socket s fds[0].events = 0; // Clear events fds[0].events = fds[0].events | POLLIN; ; // Set INPUT bit int result ; printf("Now use udp4-s3 and send a UDP message to port %s before %d sec\n", argv[1], timeout/1000 ); result = poll( fds, 1, timeout ); printf("poll( ) returns: %d\n", result); }