#include<iostream>
#include<string>
using namespace std;
struct TCP
{
bool ESTABLISHED;
int SYN=0;
int ACK=0;
int ack=0;
int seq=0;
string sIp;
string sPort;
string dIp;
string dPort;
}tcp;
class Client
{
private:
public:
void Open(string sip, string sport, string dip, string dport);
void SYN_Send();
void ACK_Send();
void close();
};
//初始化数据
void Client::Open(string sip, string sport, string dip, string dport)
{
tcp.ESTABLISHED = false;
tcp.sIp = sip;
tcp.sPort = sport;
tcp.dIp = dip;
tcp.dPort = dport;
tcp.SYN = 0;
tcp.ACK = 0;
tcp.ack = 0;
tcp.seq = 0;
}
void Client::SYN_Send()
{
if (tcp.ACK!=1&&tcp.SYN!=1)
{
tcp.SYN = 1;
tcp.seq = 100;
printf("c:<进入SYN-Send阶段>主机发起请求,参数:SYN:%d , seq:%d\n",tcp.SYN, tcp.seq);
}
}
void Client::ACK_Send(){
if (tcp.ACK == 1)
{
int seq = tcp.seq;
tcp.seq = tcp.ack;
tcp.ack = seq + 1;
tcp.ESTABLISHED = true;
printf("c:<进入Establish 阶段>向服务器确认,参数:ACK:%d , seq: %d ,ack: %d\n", tcp.ACK, tcp.seq, tcp.ack);
}
}
void Client::close()
{
tcp.ESTABLISHED = false;
printf("关闭连接...\n");
}
class Server
{
private:
string sIp;
string sPort;
string dIp;
string dPort;
public:
void Listen(string sip, string sport, string dip, string dport);
void SYN_Rcvd();
void ACK_Send();
void ACK_Rcvd();
};
//初始化数据
void Server::Listen(string sip, string sport, string dip, string dport)
{
sIp = sip;
sPort = sport;
dIp = dip;
dPort = dport;
printf("服务端监听开启.....\n");
}
void Server::SYN_Rcvd()
{
if (tcp.SYN==1)
{
printf("S:收到请求,同意建立连接...\n");
ACK_Send();
}else
{
printf("S:拒绝请求....\n");
}
}
void Server::ACK_Send(){
tcp.ACK = 1;
tcp.ack = tcp.seq + 1;
tcp.seq = 200;
printf("S:<进入SYN-RCVD状态>返回确认,参数:SYN:%d,ACK:%d,seq:%d ack:%d \n", tcp.SYN, tcp.ACK, tcp.seq, tcp.ack);
}
void Server::ACK_Rcvd()
{
if (tcp.ESTABLISHED)
{
printf("S:<进入EStablished状态>\n");
}
}
int main()
{
string serverIp = "192.168.0.1";
string serverPort = "8080";
string clientIp = "192.168.0.2";
string clientPort = "8081";
Client client;
Server server;
// 打开client 开启server监听
client.Open(clientIp,clientPort,serverIp,serverPort); //打开client
server.Listen(serverIp, serverPort,clientIp, clientPort); //开启监听
client.SYN_Send();//客户端发送请求
server.SYN_Rcvd();//服务器处理请求
client.ACK_Send();//客户端发送确认
server.ACK_Rcvd();//服务端确认
client.close();
}
C++模拟 tcp请求
最新推荐文章于 2024-06-16 13:02:31 发布