1 /*
2 * Copyright (c) 2023 Shenzhen Kaihong Digital Industry Development Co., Ltd.
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 <arpa/inet.h>
17 #include <iostream>
18 #include <netinet/in.h>
19 #include <sstream>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <sys/socket.h>
24 #include <sys/types.h>
25 #include <unistd.h>
26
27 #define MAXLINE 1024
28 #define SERV_PORT 9999
29
do_cli(FILE * fp,int sockfd,struct sockaddr * pservaddr,socklen_t servlen)30 void do_cli(FILE *fp, int sockfd, struct sockaddr *pservaddr, socklen_t servlen)
31 {
32 /* connect to server */
33 if (connect(sockfd, (struct sockaddr *)pservaddr, servlen) == -1) {
34 perror("connect error");
35 exit(1);
36 }
37
38 while (1) {
39 /* read a line and send to server */
40 static int index = 0;
41 std::string msg = "tcp/udp client send message.index=" + std::to_string(index++);
42 write(sockfd, msg.c_str(), msg.length());
43 /* receive data from server */
44 printf("send msg :%s\r\n", msg.c_str());
45 }
46 }
47
main(int argc,char ** argv)48 int main(int argc, char **argv)
49 {
50 int sockfd;
51 struct sockaddr_in servaddr;
52
53 /* check args */
54 if (argc != 2) {
55 printf("usage: udpclient <IPaddress>\n");
56 exit(1);
57 }
58
59 /* init servaddr */
60 bzero(&servaddr, sizeof(servaddr));
61 servaddr.sin_family = AF_INET;
62 servaddr.sin_port = htons(SERV_PORT);
63 if (inet_pton(AF_INET, argv[1], &servaddr.sin_addr) <= 0) {
64 printf("[%s] is not a valid IPaddress\n", argv[1]);
65 exit(1);
66 }
67
68 sockfd = socket(AF_INET, SOCK_DGRAM, 0);
69
70 do_cli(stdin, sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
71
72 return 0;
73 }