如果这不是一个有用的问题,我很抱歉。我是套接字编程的新手。我必须构建一个多播应用程序(带接收器和发送器),它只是使用多播将消息发送到一个网络中的一组主机。我使用winsock库在Windows上用C构建它。
问题是当我将receiver.exe复制到另一台计算机(在同一网络中)并运行sender.exe时,接收器无法接收该消息。我认为我的网络调制解调器需要配置一些东西来重新调整多播地址。我不明白网络如何管理多播组,多播地址“239.255.10.10”是我的随机值。
这是发件人(对于较短的源代码,我忽略了所有错误检查,因为在创建socket或setsockopt时没有发生错误,...):
#define DEFAULT_ADDR "239.255.10.10" // a random value
#define DEFAULT_PORT 4321
int main(int argc, char *argv[])
{
WSADATA WsaDat;
struct sockaddr_in mc_addr;
int sock;
char *message = "My message";
int message_len;
const char mc_ttl = 1;
WSAStartup(MAKEWORD(2,2), &WsaDat)!=0;
// Create a socket for sending to the multicast address
sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
// Set the TTL (time to live/ hop count) for the sender
setsockopt(sock, IPPROTO_IP, IP_MULTICAST_TTL, &mc_ttl, sizeof(mc_ttl));
memset(&mc_addr, 0, sizeof(mc_addr));
mc_addr.sin_family = AF_INET;
mc_addr.sin_addr.s_addr = inet_addr(DEFAULT_ADDR);
mc_addr.sin_port = htons(DEFAULT_PORT);
message_len = strlen(message);
sendto(sock, message, message_len, 0, (struct sockaddr*)&mc_addr, sizeof(mc_addr));
printf("Message sent\n");
system("PAUSE");
closesocket(sock);
WSACleanup();
}
这是接收者:
#define DEFAULT_ADDR "239.255.10.10"
#define DEFAULT_PORT "4321"
#define MAX_LEN 1024
int main(int argc, char *argv[]) {
WSADATA WsaDat;
int sock;
int flag_on = 1;
struct sockaddr_in mc_addr;
struct ip_mreq mc_req;
char message[MAX_LEN+1];
struct sockaddr_in from_addr;
int from_len;
WSAStartup(MAKEWORD(2,2), &WsaDat);
sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&flag_on, sizeof(flag_on));
memset(&mc_addr, 0, sizeof(mc_addr));
mc_addr.sin_family = AF_INET;
mc_addr.sin_addr.s_addr = htonl(INADDR_ANY);
mc_addr.sin_port = htons(atoi(DEFAULT_PORT));
bind(sock, (struct sockaddr *) &mc_addr, sizeof(mc_addr));
/* Construct an IGMP join request structure */
mc_req.imr_multiaddr.s_addr = inet_addr(DEFAULT_ADDR);
mc_req.imr_interface.s_addr = htonl(INADDR_ANY);
/* Send an ADD MEMBERSHIP message via setsockopt */
setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char*)&mc_req, sizeof(mc_req));
printf("Multicast socket ready!/nWaiting for message ...\n");
while(1) {
// clear buffer
memset(message, 0, sizeof(message));
from_len = sizeof(from_addr) ;
memset(&from_addr, 0, from_len);
recvfrom(sock, message, MAX_LEN, 0,
(struct sockaddr*)&from_addr, &from_len);
printf("Received %s from %s: ", message, inet_ntoa(from_addr.sin_addr));
}
}
答案 0 :(得分:1)
我会写
message_len = strlen(message)+ 1;
发送之前,还要发送终止空字符。
我还会尝试在同一台PC上测试发送方和接收方,以了解这是否是网络问题。