/* Send a UDP datagram to the daytime server on another host. Display the UDP datagram that comes back. */ #include #include #include #include #include #include #include #include #include void handle_sigalrm(int s); int main(int argc, char **argv) { const struct servent *const service = getservbyname("daytime", "udp"); const char name[] = "aixmita1.urz.uni-heidelberg.de"; const sa_family_t family = AF_INET; /* IP version 4 */ const struct hostent *host; int s; /* file descriptor for socket */ struct sockaddr_in address; socklen_t length = sizeof address; char buffer[100]; char dotted[100]; ssize_t n; /* number of bytes received from socket */ if (service == NULL) { fprintf(stderr, "%s: couldn't find udp service daytime\n", argv[0]); return 1; } host = gethostbyname(name); if (host == NULL) { fprintf(stderr, "%s: couldn't get IP address for %s, h_errno == %d\n", argv[0], name, h_errno); return 2; } s = socket(family, SOCK_DGRAM, 0); if (s < 0) { perror(argv[0]); return 3; } bzero(&address, sizeof address); address.sin_family = family; address.sin_port = service->s_port; address.sin_addr.s_addr = *(in_addr_t *)host->h_addr_list[0]; if (sendto(s, "", 0, 0, (const struct sockaddr *)&address, sizeof address) != 0) { perror(argv[0]); return 4; } if (getsockname(s, (struct sockaddr *)&address, &length) != 0) { perror(argv[0]); return 5; } if (inet_ntop(family, &address.sin_addr, buffer, sizeof buffer) == NULL) { perror(argv[0]); return 6; } printf("I sent an empty datagram from my port %d.\n", ntohs(address.sin_port)); /* Remain in recvfrom for no more than 15 seconds. */ if (signal(SIGALRM, handle_sigalrm) == SIG_ERR) { perror(argv[0]); return 7; } alarm(15); length = sizeof address; n = recvfrom(s, buffer, sizeof buffer, 0, (struct sockaddr *)&address, &length); if (n < 0) { perror(argv[0]); return 8; } if (inet_ntop(family, &address.sin_addr, dotted, sizeof dotted) == NULL) { perror(argv[0]); return 9; } printf("I then received a datagram containing the following %d bytes\n" "from port %d of %s", n, ntohs(address.sin_port), dotted); host = gethostbyaddr((const char *)&address.sin_addr, sizeof address.sin_addr, family); if (host != NULL) { printf(" (%s)", host->h_name); } printf("\n%*s\n", n, buffer); return EXIT_SUCCESS; } void handle_sigalrm(int s) { printf("The datagram I was waiting for didn't arrive in 15 seconds.\n"); exit(10); }