// Sending by UDP #include #include #include #include #include #include #include #include #include void main(int argc, char *argv[]) { if (argc != 3) { fprintf(stderr, "requires remotehost remoteport\n"); exit(1); } char * remote_host = argv[1]; int remote_port = atol(argv[2]); struct hostent * he = gethostbyname(remote_host); if (he == NULL) { herror("gethostbyname"); exit(1); } struct in_addr * dest_addr = (struct in_addr *) he->h_addr; 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(0); // 0 means system will pick any available port >= 1024 int r = bind(sock, (struct sockaddr *) & local, sizeof(local)); if (r < 0) { perror("bind"); exit(1); } struct sockaddr_in remote; remote.sin_len = sizeof(remote); remote.sin_family = AF_INET; remote.sin_addr = * dest_addr; remote.sin_port = htons(remote_port); const char * message = "Hello, you."; r = sendto(sock, message, strlen(message), MSG_EOR, (struct sockaddr *) & remote, sizeof(remote)); if (r < 0) { perror("sendto"); exit(1); } printf("sent %d characters of '%s'\n", r, message); close(sock); }