当前位置:   article > 正文

查找TCP连接状态_%-24s

%-24s

#include "Iphlpapi.h"
#include <malloc.h>
#include "Winsock2.h"
#include <stdlib.h>

#pragma comment(lib, "Iphlpapi.lib")
#pragma comment(lib, "ws2_32.lib")

 

static char TcpState[][32] =
{
      "???",
  "CLOSED",
  "LISTENING",
  "SYN_SENT",
  "SEN_RECEIVED",
  "ESTABLISHED",
  "FIN_WAIT",
  "FIN_WAIT2",
  "CLOSE_WAIT",
  "CLOSING",
  "LAST_ACK",
  "TIME_WAIT"
};

 

int IsMyTcpEstablished(CString strForeignTcpPort)
{
 PMIB_TCPTABLE pTcpTable = NULL;
 DWORD dwSize = 0;
 DWORD dwRetVal = ERROR_SUCCESS;
 
 struct   in_addr rip;
 struct   in_addr lip;
 char  szrip[32] = {0};  //临时存放TCP连接的本地IP
 char  szlip[32] = {0};  //临时存放TCP连接的外地IP
 CString strRip = "";
 CString strTcpState = "";
 
 //获得pTcpTable所需要的真实长度,dwSize
 if (GetTcpTable(pTcpTable, &dwSize, TRUE) == ERROR_INSUFFICIENT_BUFFER)
 {
  pTcpTable = (MIB_TCPTABLE*) malloc ((UINT) dwSize);
 }
 else
 {
  TRACE("ERROR");
  return 0;
 }
 
 TRACE("Active Connections/n/n");
    TRACE("Proto/t%-24s%-24s%s/n","Local Address","Foreign Address","State");
 
 if ((dwRetVal = GetTcpTable(pTcpTable, &dwSize, TRUE)) == NO_ERROR)
 {
  for (int i = 0; i < (int) pTcpTable->dwNumEntries; i++)
  {
   rip.S_un.S_addr = pTcpTable->table[i].dwRemoteAddr;
   lip.S_un.S_addr = pTcpTable->table[i].dwLocalAddr;
   //监听端口,远程主机端口为0,但函数返回是有值的,不知道它是怎么考虑的
   if (pTcpTable->table[i].dwState == MIB_TCP_STATE_LISTEN)  
    pTcpTable->table[i].dwRemotePort = 0;
   
   //dwLocalPort,dwRemotePort 是网络字节
   _snprintf(szlip,sizeof(szlip),"%s:%d",inet_ntoa(lip),htons((u_short)pTcpTable->table[i].dwLocalPort));
   _snprintf(szrip,sizeof(szrip),"%s:%d",inet_ntoa(rip),htons((u_short)pTcpTable->table[i].dwRemotePort));
   TRACE("  TCP/t%-24s%-24s%s/n",szlip,szrip,TcpState[pTcpTable->table[i].dwState]);
   strRip.Format("%s", szrip);
   strTcpState.Format("%s", TcpState[pTcpTable->table[i].dwState]);
   if(strForeignTcpPort == strRip && strTcpState == "ESTABLISHED")
   {
    if(pTcpTable != NULL)
    {
     free(pTcpTable);
     pTcpTable = NULL;
    }
    TRACE("Find!");
    return 1;
   }
  }
 }
 else
 {
  TRACE("/tCall to GetTcpTable failed./n");
  
  LPVOID lpMsgBuf;
  
  if (FormatMessage(
   FORMAT_MESSAGE_ALLOCATE_BUFFER |
   FORMAT_MESSAGE_FROM_SYSTEM |
   FORMAT_MESSAGE_IGNORE_INSERTS,
   NULL,
   dwRetVal,
   MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
   (LPTSTR) &lpMsgBuf,
   0,
   NULL ))
  {
   TRACE("/tError: %s", lpMsgBuf);
  }
  LocalFree( lpMsgBuf );
 }
 if(pTcpTable != NULL)
 {
  free(pTcpTable);
  pTcpTable = NULL;
 }
 TRACE("ERROR");
 return 0;
}

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/281636
推荐阅读
相关标签
  

闽ICP备14008679号