tcps.c
2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
// TCP sockek example
// TCP server
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
#include "tcp.h"
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int Sockfd;
void CloseServer()
{
close(Sockfd);
printf("\nTCP Server exit.....\n");
exit(0);
}
void main(int argc, char *argv[])
{
int newSockfd, cliAddrLen, n;
struct sockaddr_in cliAddr, servAddr; // PF_INET, IPv4
MsgType msg;
// register a signal handler
signal(SIGINT, CloseServer);
// SOCKET
// create a socket for TCP
if ((Sockfd = socket(PF_INET, SOCK_STREAM, 0)) < 0)
{
perror("socket");
exit(1);
}
// initailize a servAddr
bzero((char *)&servAddr, sizeof(servAddr));
servAddr.sin_family = PF_INET; //protocol family
servAddr.sin_addr.s_addr = htonl(INADDR_ANY); // network byte ordered 32-bit address
// receive any IP addresses
servAddr.sin_port = htons(SERV_TCP_PORT);
// BIND
if (bind(Sockfd, (struct sockaddr *)&servAddr, sizeof(servAddr)) < 0)
{
perror("bind");
exit(1);
}
// LISTEN
listen(Sockfd, 5);
printf("TCP Server started.....\n");
// kernel allocate a cliAddr ifself
cliAddrLen = sizeof(cliAddr);
while (1)
{
memset(&msg, 0, sizeof(MsgType));
// ACCEPT
newSockfd = accept(Sockfd, (struct sockaddr *)&cliAddr, &cliAddrLen);
if (newSockfd < 0)
{
perror("accept");
exit(1);
}
printf("Accept a new socket\n");
// READ
if ((n = read(newSockfd, (char *)&msg, sizeof(msg))) < 0)
{
perror("read");
exit(1);
}
printf("Received message from M2351: %s\n", msg.data);
// WRITE
//sprintf(msg.data, "This is a reply from %d.", getpid());
char aesKey[20] = {0x61, 0x62, 0x63, 0x64, 0x65,
0x66, 0x67, 0x68, 0x69, 0x6a,
0x6b, 0x6c, 0x6d, 0x6e, 0x6f,
0x70, 0x71, 0x72, 0x73, 0x74};
strcpy(msg.data, aesKey);
printf("aesKey : %s\n", msg.data);
if (write(newSockfd, (char *)&msg, sizeof(msg)) < 0)
{
perror("write");
exit(1);
}
printf("Replied.\n");
usleep(5000);
// CLOSE
close(newSockfd);
}
}