Monday 30 May 2011

TCP Port Listener

I was creating a DMZ and needed a tool to test my port forwarding I didn’t feel like downloading a program so I created this very simple piece of code to just listen on a port of my choice and print when I can make a connection. Only tests TCP (not UDP).

 

Use it as follows:

PortListener <Port>

   1: class Program
   2:    {
   3:        
   4:        static void Main(string[] args)
   5:        {
   6:            new Program().Run(args);
   7:           
   8:        }
   9:  
  10:        private void Run(string[] args)
  11:        {
  12:            int port = Int32.Parse(args[0]);
  13:            Console.WriteLine("Started listening on port: {0}", port);
  14:            var server = new TcpListener(IPAddress.Any, port);
  15:            server.Start();
  16:            server.BeginAcceptSocket(new AsyncCallback(server_onAccept), server);
  17:  
  18:            Console.WriteLine("Press any key to exit...");
  19:            Console.ReadKey();
  20:        }
  21:  
  22:        void server_onAccept(IAsyncResult ar)
  23:        {
  24:            var server = ((TcpListener)ar.AsyncState);
  25:            var socket = server.EndAcceptSocket(ar);
  26:            
  27:            Console.WriteLine(string.Format("Socket {0} Connected",socket.RemoteEndPoint.ToString()));
  28:            server.BeginAcceptSocket(new AsyncCallback(server_onAccept), server);
  29:        }
  30:    }

 

Download the source here:

 

https://github.com/TheWalkingDev/Projects/tree/master/DevTools/PortListener/PortListener

No comments:

Post a Comment