iOS oc socket 收发广播包
时间: 2023-07-25 15:17:24 浏览: 100
在iOS的Objective-C中,可以使用以下代码来收发广播包:
1. 创建UDP Socket
```objc
// 创建UDP Socket
int udpSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
// 设置广播选项
int broadcastEnable = 1;
setsockopt(udpSocket, SOL_SOCKET, SO_BROADCAST, &broadcastEnable, sizeof(broadcastEnable));
// 设置地址
struct sockaddr_in broadcastAddr;
memset(&broadcastAddr, 0, sizeof(broadcastAddr));
broadcastAddr.sin_family = AF_INET;
broadcastAddr.sin_addr.s_addr = htonl(INADDR_BROADCAST);
broadcastAddr.sin_port = htons(12345);
// 绑定端口
if (bind(udpSocket, (struct sockaddr *)&broadcastAddr, sizeof(broadcastAddr)) < 0) {
NSLog(@"Error binding socket");
return;
}
```
2. 发送广播包
```objc
// 发送广播包
const char *message = "Hello, world!";
if (sendto(udpSocket, message, strlen(message), 0, (struct sockaddr *)&broadcastAddr, sizeof(broadcastAddr)) < 0) {
NSLog(@"Error sending message");
return;
}
```
3. 接收广播包
```objc
// 接收广播包
char buffer[1024];
struct sockaddr_in fromAddr;
socklen_t fromAddrLen = sizeof(fromAddr);
int recvLen = recvfrom(udpSocket, buffer, sizeof(buffer), 0, (struct sockaddr *)&fromAddr, &fromAddrLen);
if (recvLen > 0) {
buffer[recvLen] = 0;
NSLog(@"Received message: %s", buffer);
}
```
需要注意的是,广播包的发送和接收需要在同一个网络段中,否则可能无法接收到广播包。
阅读全文