forked from RT-Thread-packages/network-sample
-
Notifications
You must be signed in to change notification settings - Fork 0
/
udpclient_sample.c
82 lines (70 loc) · 2.2 KB
/
udpclient_sample.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*
* 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);