udpclient_sample.c
/* * Copyright (c) 2006-2018, RT-Thread Development Team * * SPDX-License-Identifier: Apache-2.0 * * Change Logs: * Date Author Notes * *//* * 程序清单:udp 客户端 * * 这是一个 udp 客户端的例程 * 导出 udpclient 命令到控制终端 * 命令调用格式:udpclient URL PORT [COUNT = 10] * URL:服务器地址 PORT:端口号 COUNT:可选参数 默认为 10 * 程序功能:发送 COUNT 条数据到服务远端*/#include <rtthread.h>#include <sys/socket.h> /* 使用BSD socket,需要包含sockets.h头文件 */#include <netdb.h>#include <string.h>#include <finsh.h>const char send_data[] = "This is UDP Client from RT-Thread.\n"; /* 发送用到的数据 */void udpclient(int argc, char **argv){ int sock, port, count; struct hostent *host; struct sockaddr_in server_addr; const char *url; if (argc < 3) { rt_kprintf("Usage: udpclient URL PORT [COUNT = 10]\n"); rt_kprintf("Like: tcpclient 192.168.12.44 5000\n"); return ; } url = argv[1]; port = strtoul(argv[2], 0, 10); if (argc > 3) count = strtoul(argv[3], 0, 10); else count = 10; /* 通过函数入口参数url获得host地址(如果是域名,会做域名解析) */ host = (struct hostent *) gethostbyname(url); /* 创建一个socket,类型是SOCK_DGRAM,UDP类型 */ if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1) { rt_kprintf("Socket error\n"); return; } /* 初始化预连接的服务端地址 */ server_addr.sin_family = AF_INET; server_addr.sin_port = htons(port); server_addr.sin_addr = *((struct in_addr *)host->h_addr); rt_memset(&(server_addr.sin_zero), 0, sizeof(server_addr.sin_zero)); /* 总计发送count次数据 */ while (count) { /* 发送数据到服务远端 */ sendto(sock, send_data, strlen(send_data), 0, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)); /* 线程休眠一段时间 */ rt_thread_delay(50); /* 计数值减一 */ count --; } /* 关闭这个socket */ closesocket(sock);}MSH_CMD_EXPORT(udpclient, a udp client sample);