[Codewars] A Simplistic TCP Finite State Machine (FSM)

A Simplistic TCP Finite State Machine (FSM)

  • Time :
  • Space :
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
#include <string>
#include <vector>

using namespace std;
map<pair<string, string>, string> adj;
std::string traverse_TCP_states(const std::vector<std::string> &events){
adj[{"CLOSED","APP_PASSIVE_OPEN"}] = "LISTEN";
adj[{"CLOSED","APP_ACTIVE_OPEN"}] = "SYN_SENT";
adj[{"LISTEN","RCV_SYN"}] = "SYN_RCVD";
adj[{"LISTEN","APP_SEND"}] = "SYN_SENT";
adj[{"LISTEN","APP_CLOSE"}] = "CLOSED";
adj[{"SYN_RCVD","APP_CLOSE"}] = "FIN_WAIT_1";
adj[{"SYN_RCVD","RCV_ACK"}] = "ESTABLISHED";
adj[{"SYN_SENT","RCV_SYN"}] = "SYN_RCVD";
adj[{"SYN_SENT","RCV_SYN_ACK"}] = "ESTABLISHED";
adj[{"SYN_SENT","APP_CLOSE"}] = "CLOSED";
adj[{"ESTABLISHED","APP_CLOSE"}] = "FIN_WAIT_1";
adj[{"ESTABLISHED","RCV_FIN"}] = "CLOSE_WAIT";
adj[{"FIN_WAIT_1","RCV_FIN"}] = "CLOSING";
adj[{"FIN_WAIT_1","RCV_FIN_ACK"}] = "TIME_WAIT";
adj[{"FIN_WAIT_1","RCV_ACK"}] = "FIN_WAIT_2";
adj[{"CLOSING","RCV_ACK"}] = "TIME_WAIT";
adj[{"FIN_WAIT_2","RCV_FIN"}] = "TIME_WAIT";
adj[{"TIME_WAIT","APP_TIMEOUT"}] = "CLOSED";
adj[{"CLOSE_WAIT","APP_CLOSE"}] = "LAST_ACK";
adj[{"LAST_ACK","RCV_ACK"}] = "CLOSED";
string state = "CLOSED";
for(auto e : events) {
if(adj.count({state, e})) state = adj[{state,e}];
else return "ERROR";
}
return state;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/05/30/PS/Codewars/a-simplistic-tcp-finite-state-machine/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.