Forum Discussion
parbogast
Aug 30, 2022Copper Contributor
PowerShell Script TCP Ports
I have a script, that connect to port 443 at on a destination server, however the source port is variable and seems to user the upper register of ports. How can I or is it possible to force the scrip...
VGSandz
Dec 20, 2022Copper Contributor
You could try the below code, which is posted here in c# , https://www.codeproject.com/Questions/156019/Connect-to-remote-machine-with-TcpClient-using-a-s.aspx?display=Print
$RemoteServerIPAddress ="y.y.y.y"
$LocalPorttoUse = "xxxx"
$RemotePorttoCheck = "yyyy"
#Normalize the Local IP Addresses to use any IP.
$LocalIPAddress = [IPAddress]::Any
#Normalize the Remote IP Addresses.
$RemoteIPAddress = [System.Net.IPAddress]::Parse($RemoteServerIPAddress)
#Local endpoint and remote endpoint
$LocalEndPointAddress = New-Object Net.IPEndPoint ($LocalIPAddress,$LocalPorttoUse)
$RemoteEndPointAddress = New-Object Net.IPEndPoint ($RemoteIPAddress,$RemotePorttoCheck)
$OpenTCPClient = New-Object Net.Sockets.TcpClient($LocalEndPointAddress)
Write-Output "Conecting to $RemoteServerIPAddress ..."
try
{
$OpenTCPClient.connect($RemoteEndPointAddress)
Write-Output "Connected to Remote Server $RemoteServerIPAddress on Port $RemotePorttoCheck."
#even if we close the connection with the below call, the local port will stay occupied probably in finwait state.
#this would cause errors if the script is called in short intervals.
#there should be a check to validate if the port is absolutely free.
$OpenTCPClient.close()
}
catch
{
Write-Output "Error while establishing the connection to the remote system."
$OpenTCPClient.close()
}
Please note that this would have issues if run in short intervals of time as the local port closing would take time.
It's also suggested to use lower port numbers (unused) on source system and not to interfere with the ephemeral ports.
more on this https://learn.microsoft.com/en-us/troubleshoot/windows-server/networking/default-dynamic-port-range-tcpip-chang
- GokhankosemMay 31, 2023Copper ContributorIt is better to check network ports.
https://ipcisco.com/lesson/network-ports/