1 /*
2 * Copyright (C) 2022 HiHope Open Source Organization .
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 *
14 * limitations under the License.
15 */
16
17 #include <stdio.h>
18 #include <string.h>
19 #include <unistd.h>
20 #include "net_common.h"
21
22 static char message[128] = "";
UdpServerTest(unsigned short port)23 void UdpServerTest(unsigned short port)
24 {
25 ssize_t retval = 0;
26 int sockfd = socket(AF_INET, SOCK_DGRAM, 0); // UDP socket
27
28 struct sockaddr_in clientAddr = {0};
29 socklen_t clientAddrLen = sizeof(clientAddr);
30 struct sockaddr_in serverAddr = {0};
31 serverAddr.sin_family = AF_INET;
32 serverAddr.sin_port = htons(port);
33 serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
34
35 retval = bind(sockfd, (struct sockaddr *)&serverAddr, sizeof(serverAddr));
36 if (retval < 0) {
37 printf("bind failed, %ld!\r\n", retval);
38 printf("do_cleanup...\r\n");
39 close(sockfd);
40 }
41
42 printf("bind to port %u success!\r\n", port);
43
44 retval = recvfrom(sockfd, message, sizeof(message), 0, (struct sockaddr *)&clientAddr, &clientAddrLen);
45 if (retval < 0) {
46 printf("recvfrom failed, %ld!\r\n", retval);
47 printf("do_cleanup...\r\n");
48 close(sockfd);
49 }
50 printf("recv message {%s} %ld done!\r\n", message, retval);
51 printf("peer info: ipaddr = %s, port = %d\r\n", inet_ntoa(clientAddr.sin_addr), ntohs(clientAddr.sin_port));
52
53 retval = sendto(sockfd, message, strlen(message), 0, (struct sockaddr *)&clientAddr, sizeof(clientAddr));
54 if (retval <= 0) {
55 printf("send failed, %ld!\r\n", retval);
56 printf("do_cleanup...\r\n");
57 close(sockfd);
58 }
59 printf("send message {%s} %ld done!\r\n", message, retval);
60 SERVER_TEST_DEMO(UdpServerTest);