PortInUse

By | 2012-10-13

Working with network objects in Visual Basic can be a little daunting for newer programmers. It’s not that scary, really.

This bit of code (given here by request) will determine if a particular port is in use on the local machine. It leans on the use of Windows Sockets (winsock) to perform the check.

Private Function PortInUse(ByVal PortNumber As Integer) As _
Boolean
'*********************************************
'PURPOSE: Determine if a TCP/IP port is in use
'EXAMPLE:
'If PortInUse(21) Then
'MsgBox "The standard FTP port is in use on this machine"
'end if
'**********************************************
Dim oSocket As Object
Dim bAns As Boolean

On Error Resume Next
Set oSocket = CreateObject("MSWinsock.Winsock.1")

If Err.Number > 0 Then
Err.Raise 30000, , "Could not create winsock object"
Exit Function
End If

Err.Clear

oSocket.LocalPort = PortNumber
oSocket.Listen

'if we get this error, it means
'port is busy
bAns = Err.Number = 10048
oSocket.Close
Set oSocket = Nothing
PortInUse = bAns

End Function

Author: dwirch

Derek Wirch is a seasoned IT professional with an impressive career dating back to 1986. He brings a wealth of knowledge and hands-on experience that is invaluable to those embarking on their journey in the tech industry.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.