Link to home
Start Free TrialLog in
Avatar of Marco_Panza
Marco_Panza

asked on

Detect the TCP and UDP connections direction

Hi ,

I was create a monitor TCP/UDP connection program and work fine.I'am interesting to add a new field (direction) that show if one connection was established by a local PC or by a Host PC.The informations that I' have are:

Local IP:        ex. 192.168.01
Local Port:     ex. 1569
Remore IP:    ex. 192.168.07
Remote Port: ex. 80
State:            ex. CLOSED , LISTENING , SYN_SENT , SYN_RCVD , ESTABLISHED , LAST_ACK , CLOSING , etc..

For retrive the connections I use GetTcpTable and GetUdpTable.Can anyone help me to find the solution ?

Thanks !
Avatar of jkr
jkr
Flag of Germany image

IMHO there's no "clean" way to do that, but the port number should help - if it is a "well known" port, the connection was established by the "other" machine, e.g.

// Declare and initialize variables
PMIB_TCPTABLE pTcpTable;

pTcpTable = (MIB_TCPTABLE*) malloc(sizeof(MIB_TCPTABLE));
DWORD dwSize = 0;

// Make an initial call to GetTcpTable to
// get the necessary size into the dwSize variable
if (GetTcpTable(pTcpTable, &dwSize, TRUE) == ERROR_INSUFFICIENT_BUFFER) {
  GlobalFree(pTcpTable);
  pTcpTable = (MIB_TCPTABLE*) malloc ((UINT) dwSize);
}

// Make a second call to GetTcpTable to get
// the actual data we require
if ((dwRetVal = GetTcpTable(pTcpTable, &dwSize, TRUE)) == NO_ERROR) {
  for (int i = 0; i < (int) pTcpTable->dwNumEntries; i++) {
    printf("State: %ld\n", pTcpTable->table[i].dwState);

      if(getservbyport(pTcpTable->dwLocalPort,NULL))
            printf("...established from remote host\n");
        else
            printf("...established from local host\n");
            
  }
}
Avatar of Marco_Panza
Marco_Panza

ASKER

This is very iteresting trick !!!

The local port can help.I have find another way (but i don't known if is correct).Please send me your comment:

If the local PC accept one connection must bind first the local port and the local port is locked.
If the local PC try to connect to another PC not bind the local port and the local port is not locked.

If is true , simply I try to bind the local port with address = ADDR_ANY .

If the operation fail the connection was established from remote host (the local PC was bind and lock the local port).

I'am not a network expert.What you think ?

Thanks again !

Marco
ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
OK Very good !

Another simply question:IF the connection was established by remote PC the direction is incoming and if the connection was established by local PC the connection is oucoming.This is true ? or not ?

Thanks !

Marco
I'd say "yes", since that would be the reverse logic.