#include #include #include #include #include #include #include #include #include #include int main(int argc, const char **argv) { int udp_sock = socket(AF_INET, SOCK_DGRAM, 0); struct sockaddr_in local_addr, peer_addr; const int sock_bool = 1; socklen_t ip_len = sizeof(struct sockaddr_in); const size_t MAX_MSG = 1024; uint8_t message[MAX_MSG]; int res = 0; /* * bind to some arbitrary UDP port on localhost */ memset(&local_addr, 0, sizeof(struct sockaddr_in)); local_addr.sin_family = AF_INET; local_addr.sin_port = 0; // listen on the localhost for broadcasts if( inet_aton("127.0.0.1", &local_addr.sin_addr) == 0 ) { printf("Failed to set addr\n"); return 1; } /* * setup he broadcast target address */ memset(&peer_addr, 0, sizeof(struct sockaddr_in)); peer_addr.sin_family = AF_INET; // fixed port number for broadcasting peer_addr.sin_port = htons(30451); if( inet_aton("127.255.255.255", &peer_addr.sin_addr) == 0 ) { printf("Failed to set broadcast addr\n"); return 1; } /* * setup the socket */ if( setsockopt(udp_sock, SOL_SOCKET, SO_BROADCAST, &sock_bool, sizeof(sock_bool)) != 0 ) { printf("Failed to set broadcast option\n"); return 1; } if( bind(udp_sock, (struct sockaddr*)&local_addr, sizeof(local_addr)) != 0 ) { printf("Failed to bind to addr\n"); return 1; } if( getsockname( udp_sock, (struct sockaddr*)&local_addr, &ip_len) != 0 ) { printf("Failed to get sockname\n"); return 1; } printf("Bound to %s:%d for replies\n", inet_ntoa(local_addr.sin_addr), local_addr.sin_port ); /* send some arbitrary data */ if( sendto( udp_sock, message, 17, 0, (struct sockaddr*)&peer_addr, ip_len ) == -1 ) { perror("Failed to send broadcast"); return 1; } printf("Sent broadcast to %s:%d\n", inet_ntoa(peer_addr.sin_addr), local_addr.sin_port ); while ( 1 ) { res = recvfrom( udp_sock, message, MAX_MSG, 0, (struct sockaddr*)&peer_addr, &ip_len ); if( res == -1 ) { printf("Failed to receive message\n"); return 1; } if( ip_len != sizeof(struct sockaddr_in) ) { printf("Wrong addr len\n"); return 1; } printf("Received broadcast reply of %d bytes from %s:%d\n", res, inet_ntoa(peer_addr.sin_addr), peer_addr.sin_port ); /* * ignore actual message content */ } }