我想在基于套接字的 ios 应用程序中广播消息。我设法创建套接字、绑定、启用广播并打开非阻塞,但是当我尝试广播消息(sendto 函数)时,我收到 -1,表示错误。有谁知道为什么会这样?
int service_port = xxxx;
NSString *rawMsg = @"xxx";
// Create a socket
int socketfd = socket( AF_INET, SOCK_STREAM, 0 );
struct sockaddr_in ip4addr;
ip4addr.sin_family = AF_INET;
ip4addr.sin_port = htons(service_port);
ip4addr.sin_addr.s_addr = inet_addr("0.0.0.0");
memset(ip4addr.sin_zero, '\0', sizeof ip4addr.sin_zero);
int ret = bind(socketfd, (struct sockaddr*)&ip4addr, sizeof ip4addr);
// Set socket options
// Enable broadcast
int broadcastEnable=1;
ret = setsockopt(socketfd, SOL_SOCKET, SO_BROADCAST, &broadcastEnable, sizeof(broadcastEnable));
//turn non-blocking
ret = fcntl(socketfd, F_SETFL, O_NONBLOCK);
//udp broadcast
struct sockaddr_in address; // Make an endpoint
address.sin_family = AF_INET;
address.sin_port = htons(service_port);
address.sin_addr.s_addr = inet_addr("255.255.255.255");
memset(address.sin_zero, '\0', sizeof address.sin_zero);
ret = sendto(socketfd, (__bridge const void *)(rawMsg), strlen((__bridge const void *)(rawMsg)), 0, (struct sockaddr*)&address, sizeof address);
NSLog(@"result = %d", ret);