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.