/* Send one UDP datagram to port 7 of the host labinfu.unipv.it */ #include #include #include #include /* for gethostbyname */ #include #include #include #include void handle_sigalrm(int s); int main(int argc, char **argv) { const int s = socket(AF_INET, SOCK_DGRAM, 0); struct hostent *entry; struct sockaddr_in address; size_t length = sizeof address; struct sockaddr_in client_address; socklen_t client_length = sizeof client_address; u_short client_port; /* ephemeral port number, assigned by operating system */ char buffer[100]; ssize_t n; /* socket size */ if (s < 0) { perror(argv[0]); return 1; } entry = gethostbyname("labinfu.unipv.it"); if (entry == NULL) { fprintf(stderr, "%s: h_errno == %d\n", argv[0], h_errno); return 2; } bzero(&address, length); address.sin_family = AF_INET; address.sin_port = htons(7); address.sin_addr.s_addr = *(in_addr_t *)entry->h_addr_list[0]; /* Send a datagram. */ if (sendto(s, "Hello", 5, 0, (const struct sockaddr *)&address, sizeof address) < 0) { perror(argv[0]); return 3; } /* getsockname must come after sendto. */ if (getsockname(s, (struct sockaddr *)&client_address, &client_length) != 0) { perror(argv[0]); return 4; } client_port = ntohs(client_address.sin_port); printf("My port number is %u. (I am the client.)\n", client_port); sprintf(buffer, "/bin/netstat -a -f inet -P udp |" " awk '2 <= NR && NR <= 4 || $1 ~ /\\.%d/'\n", client_port); system(buffer); /* Remain in recvfrom for no more than 30 seconds. */ if (signal(SIGALRM, handle_sigalrm) == SIG_ERR) { perror(argv[0]); return 5; } alarm(30); n = recvfrom(s, buffer, sizeof buffer, 0, (struct sockaddr *)&address, &length); if (n < 0) { perror(argv[0]); return 6; } printf ("I received a datagram containing the %d bytes \"%.*s\"\n" "from port number %u of ", n, n, buffer, ntohs(address.sin_port)); if (inet_ntop(AF_INET, &address.sin_addr, buffer, sizeof buffer) == NULL) { perror(argv[0]); return 7; } printf("%s.\n", buffer); return EXIT_SUCCESS; } void handle_sigalrm(int s) { printf("The datagram I was waiting for never arrived.\n"); exit(8); }