在Socket中广播我的消息

时间:2013-07-22 12:30:11

标签: c sockets udp broadcasting

我正在尝试设置服务器并尝试广播消息,'这是我的消息'我把代码放在一起。这是正确的方法吗?

sock = socket(AF_INET, SOCK_DGRAM, 0);
bzero(&server, length);
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(MYPORT);

char [] broadcast = 'this is my message';
int broadcastlen = sizeof(broadcast);
if (setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &broadcast, &broadcastlen) < 0) {
    close(sock);
    error("Error in setting broadcast option");
}
if (bind(sock, (struct sockaddr*) &server, sizeof(server)) < 0) {
    close(sock);
    error("Error in BINDING");
}
bzero(&sender, length);
bcast.sin_family = AF_INET;
bcast.sin_addr.s_addr = NBCAST; // NBCAST is the broadcast address of the subnet
bcast.sin_port = htons(MYPORT);

if (sendto(sock, dateQuery, strlen(dateQuery) + 1, 0, (struct sockaddr*)&bcast, sizeof(bcast)) < 0) {
    close(sock);
    error("ERROR in sending");
}

0 个答案:

没有答案