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 <stdio.h>
17 #include "lwip/sockets.h"
18 #include "net_demo.h"
19 
20 static char g_request[] = "Hello,I am Lwip";
21 static char g_response[128] = "";
22 
TcpClientTest(const char* host, unsigned short port)23 void TcpClientTest(const char* host, unsigned short port)
24 {
25     int sockfd = socket(AF_INET, SOCK_STREAM, 0); // TCP socket
26 
27     struct sockaddr_in serverAddr = {0};
28     serverAddr.sin_family = AF_INET;  // AF_INET表示IPv4协议
29     serverAddr.sin_port = htons(port);  // 端口号,从主机字节序转为网络字节序
30     if (inet_pton(AF_INET, host, &serverAddr.sin_addr) <= 0) {  // 将主机IP地址从“点分十进制”字符串 转化为 标准格式(32位整数)
31         printf("inet_pton failed!\r\n");
32         lwip_close(sockfd);
33     }
34 
35     // 尝试和目标主机建立连接,连接成功会返回0 ,失败返回 -1
36     if (connect(sockfd, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) < 0) {
37         printf("connect failed!\r\n");
38         lwip_close(sockfd);
39     }
40     printf("connect to server %s success!\r\n", host);
41 
42     // 建立连接成功之后,这个TCP socket描述符 —— sockfd 就具有了 “连接状态”,发送、接收 对端都是 connect 参数指定的目标主机和端口
43     ssize_t retval = send(sockfd, g_request, sizeof(g_request), 0);
44     if (retval < 0) {
45         printf("send g_request failed!\r\n");
46         lwip_close(sockfd);
47     }
48     printf("send g_request{%s} %ld to server done!\r\n", g_request, retval);
49 
50     retval = recv(sockfd, &g_response, sizeof(g_response), 0);
51     if (retval <= 0) {
52         printf("send g_response from server failed or done, %ld!\r\n", retval);
53         lwip_close(sockfd);
54     }
55     g_response[retval] = '\0';
56     printf("recv g_response{%s} %ld from server done!\r\n", g_response, retval);
57     lwip_close(sockfd);
58 }
59 
NetDemoTest(unsigned short port, const char* host)60 void NetDemoTest(unsigned short port, const char* host)
61 {
62     (void) host;
63     printf("TcpClientTest start\r\n");
64     printf("I will connect to %s\r\n", host);
65     TcpClientTest(host, port);
66     printf("TcpClientTest done!\r\n");
67 }
68 
69