无法从ios应用程序广播消息

时间:2013-06-09 08:49:38

标签: iphone xcode sockets udp broadcast

我想在基于套接字的ios app中广播消息。我设法创建套接字,绑定,启用广播,并打开非阻塞,但当我尝试播放meesage(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);

0 个答案:

没有答案