#include #include #include #include #include /* for inet_ntop */ #include #include /* for getservbyname */ #include const char *progname; void handle_sigalrm(int sig); int main(int argc, char **argv) { const int s = socket(AF_INET, SOCK_DGRAM, 0); int ttl = 10; /* time to live */ int length = sizeof ttl; const struct servent *service; char name[1000] = "aixmita1.urz.uni-heidelberg.de"; const struct hostent *host; struct sockaddr_in address; socklen_t socklen = sizeof address; ssize_t n; char buffer[100]; int len; progname = argv[0]; if (s < 0) { perror(progname); return 1; } if (setsockopt(s, IPPROTO_IP, IP_TTL, &ttl, sizeof ttl) != 0) { perror(progname); return 2; } if (getsockopt(s, IPPROTO_IP, IP_TTL, &ttl, &length) != 0) { perror(progname); return 3; } printf("The time to live was set to %d.\n", ttl); service = getservbyname("daytime", "udp"); if (service == NULL) { fprintf(stderr, "%s: couldn't find udp service daytime\n", progname); return 4; } host = gethostbyname(name); if (host == NULL) { fprintf(stderr, "%s: couldn't find \"%s\", h_errno == %d\n", progname, name, h_errno); return 5; } bzero(&address, sizeof address); address.sin_family = AF_INET; address.sin_port = service->s_port; address.sin_addr.s_addr = *(in_addr_t *)host->h_addr_list[0]; /* Send a datagram. */ if (sendto(s, NULL, 0, 0, (const struct sockaddr *)&address, sizeof address) != 0) { perror(progname); return 6; } if (getsockname(s, (struct sockaddr *)&address, &socklen) != 0) { perror(progname); return 7; } printf("I sent an empty UDP datagram from my port %d.\n", ntohs(address.sin_port)); fflush(stdout); if (signal(SIGALRM, handle_sigalrm) == SIG_ERR) { perror(progname); return 8; } alarm(15); length = sizeof address; n = recvfrom(s, buffer, sizeof buffer, 0, (struct sockaddr *)&address, &length); if (n < 0) { perror(progname); return 9; } if (inet_ntop(AF_INET, &address.sin_addr, name, sizeof name) == NULL) { perror(progname); return 10; } printf("I then received a datagram containing the following %d bytes\n" "from port %d of %s", n, ntohs(address.sin_port), name); host = gethostbyaddr((const char *)&address.sin_addr, sizeof address.sin_addr, AF_INET); if (host != NULL) { printf(" (%s)", host->h_name); } printf("\n%s\n", buffer); return EXIT_SUCCESS; } void handle_sigalrm(int sig) { if (sig != SIGALRM) { fprintf(stderr, "%s: signal handler called with signal %d " "instead of %d\n", progname, sig, SIGALRM); exit(11); } fprintf(stderr, "%s: The datagram I was waiting for " "didn't arrive in 15 seconds.\n", progname); exit(12); }