Page 1 of 1

Check if network port is in use

Posted: Mon Jan 02, 2023 7:12 am
by jacdelad
Ist there a simple way to check if a network port is in use (so I don't try to use it) without interrupting someone who is using it? I found this: https://windowsloop.com/check-ports-in-use-windows-10/ which is a way on windows (via RunProgram and piping), but maybe there's a more elegant way.

Re: Check if network port is in use

Posted: Mon Jan 02, 2023 8:10 am
by Opcode
GetTcpTable2 may fit the bill for Windows at least.

Something I just tossed together (may or may not work properly :lol:):

Code: Select all

Enumeration
  #TcpConnectionOffloadStateInHost
  #TcpConnectionOffloadStateOffloading
  #TcpConnectionOffloadStateOffloaded
  #TcpConnectionOffloadStateUploading
  #TcpConnectionOffloadStateMax
EndEnumeration

Structure MIB_TCPROW2
  dwState.l
  dwLocalAddr.l
  dwLocalPort.l
  dwRemoteAddr.l
  dwRemotePort.l
  dwOwningPid.l
  dwOffloadState.l
EndStructure

Structure MIB_TCPTABLE2
  dwNumEntries.l
  table.MIB_TCPROW2[256]
EndStructure

Import "Iphlpapi.lib"
  GetTcpTable2(*TcpTable, *SizePointer, Order.b)
EndImport

ulSize = 0
*pTcpTable.MIB_TCPTABLE2 = AllocateMemory(SizeOf(MIB_TCPTABLE2))

If (dwRetVal = GetTcpTable2(*pTcpTable, @ulSize, #True)) = #ERROR_INSUFFICIENT_BUFFER
  FreeMemory(*pTcpTable)
  *pTcpTable = AllocateMemory(ulSize)
EndIf

If (dwRetVal = GetTcpTable2(*pTcpTable, @ulSize, #True)) = #NO_ERROR
  For i = 0 To *pTcpTable\dwNumEntries
    Debug "IP: " + IPString(*pTcpTable\table[i]\dwLocalAddr)
    Debug "Port: " + Str(*pTcpTable\table[i]\dwLocalPort)
    Debug "Owning Process ID: " + Str(*pTcpTable\table[i]\dwOwningPid)
  Next
EndIf

Re: Check if network port is in use

Posted: Mon Jan 02, 2023 10:43 am
by jacdelad
Aye nice, that'll do it. Thanks very much!

Re: Check if network port is in use

Posted: Thu Jan 12, 2023 4:57 am
by plouf
However if you try to open the port, you are NOT interrupting
Just fail to open

Re: Check if network port is in use

Posted: Thu Jan 12, 2023 10:47 pm
by jacdelad
This may be correct, but it's not elegant. Also, if I'm trying to find all ports in use it is time-costly and unnecessary to try every port.