• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include <errno.h>
17 #include <stdio.h>
18 #include <unistd.h>
19 
20 #include "net_demo.h"
21 #include "net_common.h"
22 
23 static char request[] = "Hello.";
24 static char response[128] = "";
25 
UdpClientTest(const char * host,unsigned short port)26 void UdpClientTest(const char* host, unsigned short port)
27 {
28     ssize_t retval = 0;
29     int sockfd = socket(AF_INET, SOCK_DGRAM, 0); // UDP socket
30 
31     struct sockaddr_in toAddr = {0};
32     toAddr.sin_family = AF_INET;
33     toAddr.sin_port = htons(port); // 端口号,从主机字节序转为网络字节序
34     if (inet_pton(AF_INET, host, &toAddr.sin_addr) <= 0) { // 将主机IP地址从“点分十进制”字符串 转化为 标准格式(32位整数)
35         printf("inet_pton failed!\r\n");
36         printf("do_cleanup...\r\n");
37         close(sockfd);
38     }
39 
40     // UDP socket 是 “无连接的” ,因此每次发送都必须先指定目标主机和端口,主机可以是多播地址
41     retval = sendto(sockfd, request, sizeof(request), 0, (struct sockaddr *)&toAddr, sizeof(toAddr));
42     if (retval < 0) {
43         printf("sendto failed!\r\n");
44         printf("do_cleanup...\r\n");
45         close(sockfd);
46     }
47     printf("send UDP message {%s} %ld done!\r\n", request, retval);
48 
49     struct sockaddr_in fromAddr = {0};
50     socklen_t fromLen = sizeof(fromAddr);
51 
52     // UDP socket 是 “无连接的” ,因此每次接收时前并不知道消息来自何处,通过 fromAddr 参数可以得到发送方的信息(主机、端口号)
53     retval = recvfrom(sockfd, &response, sizeof(response), 0, (struct sockaddr *)&fromAddr, &fromLen);
54     if (retval <= 0) {
55         printf("recvfrom failed or abort, %ld, %d!\r\n", retval, errno);
56         printf("do_cleanup...\r\n");
57         close(sockfd);
58     }
59     response[retval] = '\0';
60     printf("recv UDP message {%s} %ld done!\r\n", response, retval);
61     printf("peer info: ipaddr = %s, port = %d\r\n", inet_ntoa(fromAddr.sin_addr), ntohs(fromAddr.sin_port));
62 CLIENT_TEST_DEMO(UdpClientTest);