≡ Menu

Port forwarding in Windows and how it is used to address TCPClient class concerns

This morning I was working on writing a PowerShell code that establishes TCP connection remote server using a dynamic port. I did some coding based on TCPClient class in past (see Test Port connectivity using PowerShell), so started with the below command. Here I am trying to connect to myhost.domain.com on port 80000. – for some unknown reason the remote system is using very higher port for communication.

$Socket = New-Object Net.Sockets.TcpClient("myhost.domain.com",80000)

After executing the above command I got the error.

new-object : Exception calling “.ctor” with “2” argument(s): “Specified argument was out of the range of valid values.

Parameter name: port”

The error message is quite straight forward that the port I have given is higher than what TCPClient class can take. I did some research around this and found that 65535(0X0000FFFF) is the higher port I can establish a connection using the TCPClass method.

Now I am stuck!! Using the dotnet abilities from the Powershell is the only way to achieve stuff like this but I am hit with a limitation. Obviously I cannot ask the owner of the remote server to change their port number so started search for the alternatives.

One thing that I came to my mind is portforwarding. What if one of my server take connection from my powershell script on lower port and forward to actual remote server on the port 80000? I quickly searched on internet and figured out the below command.

netsh interface portproxy add v4tov4 listenport=9090 listenaddress=10.10.10.100 connectport=80000 connectaddress=10.10.10.241

After this, I changed my powershell code to connect to 10.10.10.100 on port 9090 instead of myhost.domain.com on port 80000. It worked like a champ and I could able to make a connection to the real target server and able to read/write data through that socket.

Felt really wonderful after finding this and eager to share this with my blog readers. Hope you will find it useful.

{ 3 comments… add one }
  • Chetan Kumar Tammala February 15, 2014, 3:06 pm

    Thank you for sharing this Sitaram! out-of-box solutions like these will definitely help a lot of people.

    Thanks,
    Chetan

  • Bill Lortz April 26, 2014, 2:16 am

    There is something strange going on here. The TCP (and UDP) protocols have a 16 bit field for port number. That field is treated as an unsigned integer and has a maximum value of 65535. I don’t see how a webserver could be setup on a higher port than that. I suspect that what is really happening is that only the lower 16 bits are being used and therefore the webserver is truly listening on port 14464 (logical AND of 80000 and 65535).

    • Sitaram Pamarthi April 29, 2014, 6:54 am

      Bill, you are 100% correct. The server is listening on 14464 only. Not quite clear why the app team said listening port as 80000. Does it provide any extra security?

Leave a Comment