// receive by UDP #include #include #include #include #include #include #include #include #include void main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "requires localport\n"); exit(1); } int local_port = atol(argv[1]); int sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock < 0) { perror("socket"); exit(1); } struct sockaddr_in local; local.sin_len = sizeof(local); local.sin_family = AF_INET; local.sin_addr.s_addr = htonl(INADDR_ANY); local.sin_port = htons(local_port); int r = bind(sock, (struct sockaddr *) & local, sizeof(local)); if (r < 0) { perror("bind"); exit(1); } struct sockaddr_in remote; bzero(& remote, sizeof(remote)); unsigned int size = sizeof(remote); char message[1000]; r = recvfrom(sock, message, sizeof(message) - 1, 0, (struct sockaddr *) & remote, & size); if (r < 0) { perror("recvfrom"); exit(1); } message[r]=0; printf("from %s port %d, %d characters: '%s'\n", inet_ntoa(remote.sin_addr), ntohs(remote.sin_port), r, message); close(sock); }