ios oc socket广播包发送与接收
时间: 2023-08-18 22:08:36 浏览: 248
iOS Objective-C中发送和接收广播包需要使用Socket编程。以下是一个简单的发送和接收广播包的示例代码:
发送广播包:
```objc
// 创建UDP Socket
int fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd < 0) {
NSLog(@"create socket failed");
return;
}
// 设置广播地址
int opt = 1;
setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &opt, sizeof(opt));
// 设置目标地址和端口号
struct sockaddr_in destAddr;
memset(&destAddr, 0, sizeof(destAddr));
destAddr.sin_family = AF_INET;
destAddr.sin_port = htons(8888);
destAddr.sin_addr.s_addr = inet_addr("255.255.255.255"); // 广播地址
// 发送数据
char *msg = "hello world";
sendto(fd, msg, strlen(msg), 0, (struct sockaddr *)&destAddr, sizeof(destAddr));
// 关闭Socket
close(fd);
```
接收广播包:
```objc
// 创建UDP Socket
int fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd < 0) {
NSLog(@"create socket failed");
return;
}
// 设置广播地址
int opt = 1;
setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &opt, sizeof(opt));
// 设置本地地址和端口号
struct sockaddr_in localAddr;
memset(&localAddr, 0, sizeof(localAddr));
localAddr.sin_family = AF_INET;
localAddr.sin_port = htons(8888);
localAddr.sin_addr.s_addr = INADDR_ANY;
// 绑定Socket
if (bind(fd, (struct sockaddr *)&localAddr, sizeof(localAddr)) < 0) {
NSLog(@"bind socket failed");
close(fd);
return;
}
// 接收数据
char buf[1024];
struct sockaddr_in fromAddr;
socklen_t fromLen = sizeof(fromAddr);
ssize_t n = recvfrom(fd, buf, sizeof(buf), 0, (struct sockaddr *)&fromAddr, &fromLen);
if (n > 0) {
buf[n] = '\0';
NSLog(@"received msg: %s", buf);
}
// 关闭Socket
close(fd);
```
注意:发送广播包需要设置Socket的SO_BROADCAST选项,接收广播包需要绑定本地地址和端口号。在接收数据时,可以通过fromAddr获取发送方的地址和端口号。
阅读全文