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