一種關閉TCP連線的方法
利用IpHlpApi.h中SetTcpEntry函式可以修改單條TCP連線的資訊,我們可以將TCP連線狀態設為已刪除就可以達到關閉TCP連線的效果。
/*
@param szIpAddr 遠端連線ip地址
@param nPort 遠端連線的埠號
*/
void CloseTcpConnection(LPCSTR szIpAddr,int nPort)
{
PMIB_TCPTABLE pTcpTable = NULL;
DWORD dwSize = 0;
if (GetTcpTable(pTcpTable,&dwSize,TRUE) == ERROR_INSUFFICIENT_BUFFER)
{
//pTcpTable = (PMIB_TCPTABLE)new BYTE[dwSize];
pTcpTable = (PMIB_TCPTABLE)malloc(dwSize);
}
DWORD dwRet = GetTcpTable(pTcpTable,&dwSize,TRUE);
if (dwRet == NO_ERROR)
{
for (int i=0; i<pTcpTable->dwNumEntries; i++)
{
in_addr in;
in.s_addr = pTcpTable->table[i].dwLocalAddr;
cout<<inet_ntoa(in)<<":"<<htons(pTcpTable->table[i].dwLocalPort);
in.s_addr = pTcpTable->table[i].dwRemoteAddr;
cout<<" --- "<<inet_ntoa(in)<<":"<<htons(pTcpTable->table[i].dwRemotePort)<<endl;
if (stricmp(inet_ntoa(in),szIpAddr) && (htons(pTcpTable->table[i].dwRemotePort) == nPort))
{
MIB_TCPROW mTcpRow = pTcpTable->table[i];
mTcpRow.dwState = MIB_TCP_STATE_DELETE_TCB;
SetTcpEntry(&mTcpRow);
}
}
}
if (pTcpTable != NULL)
free(pTcpTable);
}