Quick and Dirty TCP Listener Port

Thu, May 22, 2008

Technology

Following up on my previous post about AllScoop's excellent TCP Listener tool… I decided to look into a change for the application that would allow me to see the IP Address of the connected client.  I did a little digging and found an article in the Microsoft forums that had a recommendation to do a DirectCast from the Net.IPEndPoint.  Armed with this information I decided to try and build a quick and dirty TCP listener that would validate if this suggestion would actually work.  Here is the code that I ended up with:

Imports System.Net.Sockets
Imports System.Text

Module Module1

  Sub Main()
    Dim port As Integer = 5010
    Dim text As String = "Hello"
    Dim listener As New TcpListener(port)
    Try
      listener.Start()

      Console.WriteLine("Added listening on port " & port.ToString)
      Do While True
        Dim client As TcpClient = listener.AcceptTcpClient
        Dim ipAddress As String = DirectCast(client.Client.RemoteEndPoint, Net.IPEndPoint).Address.ToString
        Console.WriteLine("Connection from {0} on port {1}", ipAddress, port.ToString)
        Dim stream As NetworkStream = client.GetStream
        Dim bytes As Byte() = Encoding.ASCII.GetBytes(
[/text]

)
stream.Write(bytes, 0, bytes.Length)
stream.Close()
client.Close()
Loop
Catch exception1 As Exception
Console.WriteLine("An error occured, the port may be in use")
End Try

End Sub

End Module

The special sauce this code is on line 16 where the IP Address is pulled from the client's RemoteEndPoint.  I have forwarded this over to AllScoop and hopefully we can see an update to their TCP Listener code.

Comments are closed.