UDP广播
项目编写¶
- 在
applications/genkipi/app
下新建udp_broadcast
文件夹 - 在
udp_broadcast
下新建main.c
文件 - 在
udp_broadcast
下新建BUILD.gn
文件
代码部分¶
main.c
文件内容
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "genki_wifi_sta.h"
#include "lwip/sockets.h"
#define WIFI_SSID "itheima"
#define WIFI_PASSWORD "12345678"
#define HOSTNAME "itcast"
static void udp_task(void) {
wifi_sta_connect(WIFI_SSID, WIFI_PASSWORD, HOSTNAME);
// udp create
int sock_fd;
int ret;
sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
if (sock_fd < 0) {
perror("sock_fd create error\r\n");
return;
}
// set broadcast mode
int yes = 1;
ret = setsockopt(sock_fd, SOL_SOCKET, SO_BROADCAST, (char *) &yes, sizeof(yes));
if (ret == -1) {
perror("setsockopt error\r\n");
return;
}
// config broadcast addr
struct sockaddr_in broadcast_addr;
socklen_t broadcast_addr_len = sizeof(broadcast_addr);
memset((void *) &broadcast_addr, 0, broadcast_addr_len);
broadcast_addr.sin_family = AF_INET;
broadcast_addr.sin_addr.s_addr = htonl(INADDR_BROADCAST);
broadcast_addr.sin_port = htons(8080);
char *msg = "hello world";
while (1) {
ret = sendto(sock_fd, msg, strlen(msg), 0, (struct sockaddr *) &broadcast_addr, broadcast_addr_len);
usleep(1 * 1000 * 1000);
}
}
static void start(void) {
osThreadAttr_t attr;
attr.name = "udp_broadcast";
attr.attr_bits = 0U;
attr.cb_mem = NULL;
attr.cb_size = 0U;
attr.stack_mem = NULL;
attr.stack_size = 1024 * 4;
attr.priority = 25;
if (osThreadNew((osThreadFunc_t) udp_task, NULL, &attr) == NULL) {
printf("Create udp broadcast task Failed!\r\n");
}
}
APP_FEATURE_INIT(start);
项目Build.gn¶
udp_broadcast
目录下 BUILD.gn
内容为
static_library("udp_broadcast") {
sources = [
"main.c"
]
include_dirs = [
"//utils/native/lite/include",
"//base/iot_hardware/peripheral/interfaces/kits",
"//device/itcast/genkipi/interfaces/kits"
]
}
外部Build.gn¶
udp_broadcast
文件夹上一级目录下BUILD.gn
内容为
import("//build/lite/config/component/lite_component.gni")
lite_component("app") {
features = [
"udp_broadcast"
]
}