• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (c) 2022 Huawei Device Co., Ltd.
4  *
5  * Description: Demo example of NewIP tcp server.
6  *
7  * Author: Yang Yanjun <yangyanjun@huawei.com>
8  *
9  * Data: 2022-09-06
10  */
11 #include <stdio.h>
12 #include <unistd.h>
13 #include <string.h>
14 #include <arpa/inet.h>
15 #include <sys/socket.h>
16 
17 #define __USE_GNU
18 #include <sched.h>
19 #include <pthread.h>
20 
21 #include "nip_uapi.h"
22 #include "nip_lib.h"
23 #include "newip_route.h"
24 
recv_send(void * args)25 void *recv_send(void *args)
26 {
27 	int cfd, ret;
28 	char buf[BUFLEN] = {0};
29 
30 	memcpy(&cfd, args, sizeof(int));
31 	for (int i = 0; i < PKTCNT; i++) {
32 		int recv_num = recv(cfd, buf, PKTLEN, MSG_WAITALL);
33 
34 		if (recv_num < 0) {
35 			perror("recv");
36 			goto END;
37 		} else if (recv_num == 0) { /* no data */
38 			;
39 		} else {
40 			printf("Received -- %s --:%d\n", buf, recv_num);
41 			ret = send(cfd, buf, recv_num, 0);
42 			if (ret < 0) {
43 				perror("send");
44 				goto END;
45 			}
46 			printf("Sending  -- %s --:%d\n", buf, recv_num);
47 		}
48 	}
49 END:	close(cfd);
50 	return NULL;
51 }
52 
main(int argc,char ** argv)53 int main(int argc, char **argv)
54 {
55 	pthread_t th;
56 	int fd, cfd, addr_len;
57 	struct sockaddr_nin si_local;
58 	struct sockaddr_nin si_remote;
59 
60 	fd = socket(AF_NINET, SOCK_STREAM, IPPROTO_TCP);
61 	if (fd < 0) {
62 		perror("socket");
63 		return -1;
64 	}
65 
66 	memset((char *)&si_local, 0, sizeof(si_local));
67 	si_local.sin_family = AF_NINET;
68 	si_local.sin_port = htons(TCP_SERVER_PORT);
69 	// 2-byte address of the server: 0xDE00
70 	si_local.sin_addr.NIP_ADDR_FIELD8[INDEX_0] = 0xDE;
71 	si_local.sin_addr.NIP_ADDR_FIELD8[INDEX_1] = 0x00;
72 	si_local.sin_addr.bitlen = NIP_ADDR_BIT_LEN_16; // 2-byte: 16bit
73 
74 	if (bind(fd, (const struct sockaddr *)&si_local, sizeof(si_local)) < 0) {
75 		perror("bind");
76 		goto END;
77 	}
78 	printf("bind success, addr=0x%02x%02x, port=%d\n",
79 	       si_local.sin_addr.NIP_ADDR_FIELD8[INDEX_0],
80 	       si_local.sin_addr.NIP_ADDR_FIELD8[INDEX_1], TCP_SERVER_PORT);
81 
82 	if (listen(fd, LISTEN_MAX) < 0) {
83 		perror("listen");
84 		goto END;
85 	}
86 
87 	addr_len = sizeof(si_remote);
88 	memset(&si_remote, 0, sizeof(si_remote));
89 	cfd = accept(fd, (struct sockaddr *)&si_remote, (socklen_t *)&addr_len);
90 	pthread_create(&th, NULL, recv_send, &cfd);
91 	/* Wait for the thread to end and synchronize operations between threads */
92 	pthread_join(th, NULL);
93 END:	close(fd);
94 	return 0;
95 }
96 
97