如何在Linux中使用C进行UDP广播?
在许多IP堆栈中,例如Linux,此代码不起作用.您的套接字必须具有广播权限.试试这个:
bcast_sock = socket(AF_INET, SOCK_DGRAM, 0); int broadcastEnable=1; int ret=setsockopt(bcast_sock, SOL_SOCKET, SO_BROADCAST, &broadcastEnable, sizeof(broadcastEnable)); /* Add other code, sockaddr, sendto() etc. */
放松是正确的,除了你应该使用'sendto'
这是一个示例,假设您已经有一个套接字.它取自clamav
static void broadcast(const char *mess) { struct sockaddr_in s; if(broadcastSock < 0) return; memset(&s, '\0', sizeof(struct sockaddr_in)); s.sin_family = AF_INET; s.sin_port = (in_port_t)htons(tcpSocket ? tcpSocket : 3310); s.sin_addr.s_addr = htonl(INADDR_BROADCAST); cli_dbgmsg("broadcast %s to %d\n", mess, broadcastSock); if(sendto(broadcastSock, mess, strlen(mess), 0, (struct sockaddr *)&s, sizeof(struct sockaddr_in)) < 0) perror("sendto"); }