none
How to check if a port is open on a particular IP address

    Question

  • Hi all,

    I have an application which need to send data to particular system on specific port. But the application gets hang if the target system port is closed.

    I Want to know if a particular Port is open on a specific IP address so that i can continue my next task.


    PBL (Visual Studio 2010 Ultimate)
    Thursday, November 24, 2011 2:36 PM

All replies

  • We need to see how you are opening the port.  When posting code make sure that the names are changed if needed.
    Serial Port      Random       Check Internet Connection      Microsoft® Community Contributor 2011
    Thursday, November 24, 2011 4:35 PM
  • dbasnett,

    Below is the class that i am using for TCP chat.

    This i could able to get and using in my application from other post

    http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/435cce94-3a5f-4635-bac3-8e1964422539

    Public Class TCP_Messaging
        Public Event DataReceived(ByVal txt As String)
        Public Event Connection(ByVal cStatus As Boolean)
        Public Event sendOK(ByVal sStatus As Boolean)
        Public Event recOK(ByVal sReceived As Boolean)
    
        Private serverRuns As Boolean
        Private server As TcpListener
        Private sc As SynchronizationContext
        Private isConnected, receiveStatus, sendStatus As Boolean
    
        Public Sub connect(ByVal thisaddress As String, ByVal thisport As Integer)
    
            sc = SynchronizationContext.Current
    
            Try
    
                server = New TcpListener(IPAddress.Parse(thisaddress), thisport)
                'MsgBox("connected...")
    
    
            Catch ex As Exception
    
                MsgBox("server create: " & ex.Message, MsgBoxStyle.Exclamation)
    
            End Try
            Try
                With server
                    .Start()
                    .BeginAcceptTcpClient(New AsyncCallback(AddressOf DoAccept), server)
                    isConnected = True
                End With
            Catch ex As Exception
                MsgBox("server listen: " & ex.Message, MsgBoxStyle.Exclamation)
                isConnected = False
            Finally
                RaiseEvent Connection(isConnected)
            End Try
        End Sub
    
        Public Sub disconnect()
    
            Try
    
                isConnected = False
                server.Stop()
    
            Catch ex As Exception
    
                MsgBox("disConnect server: " & ex.Message, MsgBoxStyle.Exclamation)
                isConnected = True
    
            Finally
    
                RaiseEvent Connection(isConnected)
    
            End Try
    
    
        End Sub
    
        Public Sub SendData(ByVal txt As String, ByVal targetAddress As String, ByVal targetPort As Integer)
    
            Dim ClientSocket = New TcpClient
            ClientSocket.SendTimeout = 20
            With ClientSocket
                Try
                    .Connect(IPAddress.Parse(targetAddress), targetPort)
                    Dim data() As Byte = Encoding.ASCII.GetBytes(txt)
                    .NoDelay = True
                    .GetStream.Write(data, 0, data.Length)
                    .GetStream.Close()
    
                    .Close()
                    sendStatus = True
    
                Catch ex As Exception
                    
                    'MsgBox("sendData: " & ex.Message, MsgBoxStyle.Exclamation)
                    
    
                    sendStatus = False
    
                Finally
    
                    RaiseEvent sendOK(sendStatus)
    
                End Try
    
            End With
    
        End Sub
        Private Sub DoAccept(ByVal ar As IAsyncResult)
    
            Dim sb As New StringBuilder
            Dim Buff() As Byte
            Dim DataLen As Integer
    
            Dim Listner As TcpListener
            Dim ClientSocket As TcpClient
    
            If Not isConnected Then Exit Sub
    
            Try
                Listner = CType(ar.AsyncState, TcpListener)
                ClientSocket = Listner.EndAcceptTcpClient(ar)
                ClientSocket.ReceiveTimeout = 50
    
            Catch ex As ObjectDisposedException
                MsgBox("DoAccept ObjectDisposedException " & ex.Message, MsgBoxStyle.Exclamation)
                Exit Sub
            End Try
    
            Try
    
                With ClientSocket
    
                    DataLen = 0
    
                    While DataLen = 0
    
                        DataLen = .Available
    
                    End While
    
                    Buff = New Byte(DataLen - 1) {}
    
                    .GetStream.Read(Buff, 0, Buff.Length)
                    sb.Append(Encoding.ASCII.GetString(Buff, 0, Buff.Length))
                    .Close()
    
                End With
    
                receiveStatus = True
    
            Catch ex As TimeoutException    'Time out exception
    
                MsgBox("doAcceptData timeout: " & ex.Message, MsgBoxStyle.Exclamation)
                receiveStatus = False
                ClientSocket.Close()
                Exit Sub
    
            Catch ex As Exception
    
                MsgBox("doAcceptData: " & ex.Message, MsgBoxStyle.Exclamation)
                receiveStatus = False
                ClientSocket.Close()
                Exit Sub
    
            Finally
    
                RaiseEvent recOK(receiveStatus)
    
            End Try
            ' post data
            sc.Post(New SendOrPostCallback(AddressOf OnDataReceived), sb.ToString)
            ' start new read
            server.BeginAcceptTcpClient(New AsyncCallback(AddressOf DoAccept), server)
    
        End Sub
    
        Public Sub OnDataReceived(ByVal state As Object)
    
            RaiseEvent DataReceived(state.ToString)
    
        End Sub
    
        Public Sub receiveData(ByVal txt As String) Handles Me.DataReceived
    
    'Frm_MessagePopUp is the form to display the received message in Label : lbl_msg
    
            If Frm_MessagePopUp.Visible Then
                Frm_MessagePopUp.Dispose()
            End If
    
            Frm_MessagePopUp.lbl_msg.Text = txt
    
            Frm_MessagePopUp.Show()
    
        End Sub
    
    End Class
    


    In the form load event i am using below code

    Dim WithEvents myChat As New TCP_Messaging
    
    Private Sub MDI_ShowTime_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    
            InitilizeMessaging()    'Initilize the Messaging service by opening the ports for socket connection over LAN
    
        End Sub
    
    
    Private Sub InitilizeMessaging()
    
            strHostName = Dns.GetHostName       'Retriving the current system name
    
            Dim ipEntry As IPHostEntry = Dns.GetHostEntry(strHostName)
    
            IPaddr = ipEntry.AddressList
    
            Dim i As Integer
    
            For i = 0 To IPaddr.Length - 1
    
                If IPaddr(i).AddressFamily = AddressFamily.InterNetwork Then
    
                    Exit For
    
                End If
            Next
    
            myChat.connect(IPaddr(i).ToString, 1863)
    
        End Sub
    
    
    


    I could able to send and receive the message without any hang  if the application is running on both the ends (system1 and system2). The problem arises when the application is closed at system1 while system2 is trying to send the message to system1. it hangs for nearly 18sec, which was explained in below link

    http://support.microsoft.com/kb/200770/en-us?fr=1

    So i was trying to check if the port (for ex 1863 which i used in code) on receiving system is open, so that i can continue sending message else skip that process and continue other process in the code.

    if i am not clear let me know, i will try to explain where you have any doubt.

    All your support is most valuable.


    PBL (Visual Studio 2010 Ultimate)
    Friday, November 25, 2011 3:24 AM
  • It seems that you are opening and closing the connection before every send.  Why not open the connection and pass messages as needed.  Both ends should be able to terminate the connection.

     

    I'll try to look at this in more detail, but that was what jumped out at me.


    Serial Port      Random       Check Internet Connection      Microsoft® Community Contributor 2011
    Friday, November 25, 2011 12:27 PM
  • It seems that you are opening and closing the connection before every send.  Why not open the connection and pass messages as needed.  Both ends should be able to terminate the connection.

     

    I'll try to look at this in more detail, but that was what jumped out at me.


    Serial Port      Random       Check Internet Connection      Microsoft® Community Contributor 2011

    dbasnett,

    I am not opening and closing the connection before every send.

    You can see at my form_load when InitilizeMesaging is called it opens a connection on the system where the application is launched. with which its in open mode to receive the messages. when we need to send the message to other system, it connects to that system and same port and sends messages. this is done at below code...

     Public Sub SendData(ByVal txt As String, ByVal targetAddress As String, ByVal targetPort As Integer)
    
            Dim ClientSocket = New TcpClient
            ClientSocket.SendTimeout = 20
            With ClientSocket
                Try
                    .Connect(IPAddress.Parse(targetAddress), targetPort)
                    Dim data() As Byte = Encoding.ASCII.GetBytes(txt)
                    .NoDelay = True
                    .GetStream.Write(data, 0, data.Length)
                    .GetStream.Close()
    
                    .Close()
                    sendStatus = True
    
                Catch ex As Exception
                    
                    'MsgBox("sendData: " & ex.Message, MsgBoxStyle.Exclamation)
                    
    
                    sendStatus = False
    
                Finally
    
                    RaiseEvent sendOK(sendStatus)
    
                End Try
    
            End With
    
        End Sub

    if the target system is not running the application then the systems will try to connect but fails @ below line of statment

    .Connect(IPAddress.Parse(targetAddress), targetPort)

     

    Hope i you understood how the connection is made...


    PBL (Visual Studio 2010 Ultimate)
    Saturday, November 26, 2011 3:54 AM
  • It sure looks to me like you are creating a new socket, connecting, sending, and closing every time.  Maybe I should not have said open...

    @AP - not me, and certainly not for that. 

    Serial Port      Random       Check Internet Connection      Microsoft® Community Contributor 2011
    Saturday, November 26, 2011 11:33 AM
  • Form with a button and two textboxes (IP_HostTextBox and PortTextBox)

     

     

    Public Class Form1
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim ipa As System.Net.IPAddress = Nothing
            Dim portno As Integer = CInt(PortTextBox.Text)
            If System.Net.IPAddress.TryParse(IP_HostTextBox.Text, ipa) Then
                ipa = System.Net.IPAddress.Parse(IP_HostTextBox.Text)
            Else
                ipa = System.Net.Dns.GetHostAddresses(IP_HostTextBox.Text)(0)
            End If
            Try
                Dim sock As System.Net.Sockets.Socket = New System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp)
                sock.Connect(ipa, portno)
                If sock.Connected = True Then
                    'Port is in use and connection is successful
                    MessageBox.Show("Port is Open")
                    sock.Close()
                End If
            Catch ex As Exception
                MessageBox.Show("Port is Closed")
            End Try
        End Sub
    
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            IP_HostTextBox.Text = "ftp-linux.cc.gatech.edu" ' used as a test, known reliable host
             PortTextBox.Text = "21" ' Standard FTP port for above host
         End Sub
    End Class
    

    You can put an IP address in that TextBox also. No real error checking is implemented.

    Sunday, November 27, 2011 4:56 PM
  • Devon,

    I checked your suggestion and its working fine.

    Can u suggest any other alternate for my process using sockets instead mine.

    If so i will open an other thread for this.


    PBL (Visual Studio 2010 Ultimate)
    Monday, November 28, 2011 11:48 AM
  • Nothing that I'd call very reliable. I sometimes use plain old telnet

    telnet hostname port#

    then if it connects at all I try a few keys, like

    HELO

    LIST

    HELP

    QUIT

    and see if whatever is on the other end sends anything back. Sometimes telnet connects, the server sends back a response that clears the screen, then nothing happens for a long time until the server has had enough and disconnects. Not very useful.

     

    Monday, November 28, 2011 4:34 PM
  • Because Telnet is a protocol and you are not responding properly to the messages required for the correct connection.


    RFC 854


    Serial Port      Random       Check Internet Connection      Microsoft® Community Contributor 2011
    Monday, November 28, 2011 8:41 PM
  • If you get this:

    C:\>telnet Z.Z.Z.Z PPPP
    Connecting To Z.Z.Z.Z...Could not open connection to the host, on port pppp: Connect failed

    It's likely that there is nothing listening at Z.Z.Z.Z on port pppp

    If you get a response of any kind, text or screen clear etc., there is something there and the port is open.

    Monday, November 28, 2011 11:45 PM
  • Devon,

    I tried implementing ur suggestion in my chat . I am uploading my chat program in the below link.

    https://skydrive.live.com/#cid=58C45CD8088B910B&id=58C45CD8088B910B%21129

    when i launch the application and press connect button with the default values(Source & target are the same system). it conects to the target IP and port

    if i send message by hitting enter at the message text box (tbin). i could able to send the message

    in the message window it shows out message with -----> and incoming message with <----

    But i am not able to send message after i click the button Chk Port (where i applied your code to check, it reports correctly if the tatget port is open/close). Can u check the code and update where i am going wrong (is ur socket.close is closing the port on target machine...?).

     


    PBL (Visual Studio 2010 Ultimate)
    Tuesday, November 29, 2011 3:11 AM