1 /*
2  * Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include <stdlib.h>
17 #include <stdio.h>
18 #include <string.h>
19 #include <errno.h>
20 #include "lwip/netifapi.h"
21 
22 #define CLIENT_SOCKET_CREATE_FAILED (-1)
23 #define UDP_SERVER_PORT (6655) /* TEST Port */
24 #define UDP_CLIENT_PORT (5566) /* TEST Port */
25 
26 #define UDP_RECV_BUF_LEN (255)
27 
UdpClientDemo(void)28 int UdpClientDemo(void)
29 {
30     struct sockaddr_in sin = {0};
31     struct sockaddr_in serverAddr = {0};
32     /* create socket */
33     int sClient = socket(AF_INET, SOCK_DGRAM, 0);
34     if (sClient == CLIENT_SOCKET_CREATE_FAILED) {
35         printf("create socket Fialed\r\n");
36         close(sClient);
37         return CLIENT_SOCKET_CREATE_FAILED;
38     }
39     // 本地主机ip和端口号
40     sin.sin_family = AF_INET;
41     sin.sin_port = htons(UDP_SERVER_PORT); /* server端口号6655 */
42     sin.sin_addr.s_addr = inet_addr("XXX.XXX.X.XXX");
43     int ret = bind(sClient, (struct sockaddr*)&sin, sizeof(sin));
44     if (ret < 0) {
45         printf("client bind failed %d, %s\r\n", __LINE__, errno);
46     }
47     // 对方ip和端口号
48     serverAddr.sin_family = AF_INET;
49     serverAddr.sin_port = htons(UDP_CLIENT_PORT); /* client端口号5566 */
50     serverAddr.sin_addr.s_addr = inet_addr("XXXX.XXX.X.XXX");
51 
52     int len = sizeof(sin);
53     char *sendData = "这是客户端的消息\r\n";
54     while (1) {
55         sendto(sClient, sendData, strlen(sendData), 0, (struct sockaddr*)&serverAddr, len);
56         char recvData[UDP_RECV_BUF_LEN] = {0};
57         /* buff大小设置为255 */
58         int recvLen = recvfrom(sClient, recvData, UDP_RECV_BUF_LEN, 0, (struct sockaddr*)&serverAddr, &len);
59         if (recvLen) {
60             printf("recv_data = %s\r\n", recvData);
61         }
62     }
63     close(sClient);
64     return 0;
65 }