Need to check a Socket but with a source IP

$socketC = New-object Net.Sockets.TcpClient

Need to check a Socket but with a source IP. Above code is connected form “localhost”. Please help how to put remote IP instead of localhost?


Please elaborate what you’re trying to do. I assume from your example code that you’re trying to execute port checks towards Active Directory Domain Controllers.

Please keep in mind that every connection leaving your test machine to a remote IP will have the source IP of the network adapter that has an explicit route or default gateway. The localhost IP ( is not used to communicate with remote machines (ever).


If you are trying to connect to machine C from machine B and your local machine is machine A I don’t think that will work they way you want. My understanding of the Connect method is that you connect to a remote machine from your local machine -

If you can explain what you are trying to achieve we may be able to help

The “Client” property of the object type System.Net.Sockets.TcpClient contains useful information, as you can see below :

$socketC | Select-Object -ExpandProperty Client

Available           : 0
LocalEndPoint       :
RemoteEndPoint      :
Handle              : 1760
Blocking            : True
UseOnlyOverlappedIO : False
Connected           : True
AddressFamily       : InterNetwork
SocketType          : Stream
ProtocolType        : Tcp
IsBound             : True
ExclusiveAddressUse : False
ReceiveBufferSize   : 8192
SendBufferSize      : 8192
ReceiveTimeout      : 0
SendTimeout         : 0
LingerState         : System.Net.Sockets.LingerOption
NoDelay             : False
Ttl                 : 128
DontFragment        : True
MulticastLoopback   :
EnableBroadcast     :
DualMode            : 

So, if you just want the source and remote endpoints :

$socketC | Select-Object -ExpandProperty client | Select-Object -Property LocalEndPoint, RemoteEndPoint

LocalEndPoint                                 RemoteEndPoint                      

Or, if you want only the source and remote IP addresses, without the port numbers :

$socketC | Select-Object -Property @{N="LocalIP";E={$_.Client.LocalEndPoint.Address }}, @{N="RemoteIP";E={$_.Client.RemoteEndPoint.Address }}

LocalIP                                            RemoteIP                                


I am trying to check a Socket to machine C(IP & port) from machine B (IP) and my local machine is machine A.

Your code would have to run on machine B. I don’t think remoting will work for you - you’re going to hit the second hop problem. Why does machine C have to be checked from B? Why not run the code on A?

Second hop won’t be an issue here; there’s no authentication happening to “machine C”. As long as you have remoting enabled on “machine B”, you can just use Invoke-Command.

Invoke-Command will be connected via remote System. Need something from locally.

That doesn’t make any sense. You’re saying you want to test a connection from both a remote machine, and “from locally.” What does that mean, exactly?

Need to check a connection COMA(web server)------COMB(Client PC). Need to check from COMC without " Enter-PSSession" or “Invoke-Command


I’ve seen all sorts of problems trying to work against a third machine so I’m not 100% convinced that there isn’t any issue

Need to check for 6000 PC so want to aviod invoke-command 6000 time. Will try some foreach if we can define the source IP.

Biswajit wrote:Need to check for 6000 PC so want to aviod invoke-command 6000 time. Will try some foreach if we can define the source IP.

Well, good luck with that. :slight_smile: If you want to actually check the connection from 6000 source endpoints, then you need to make the code execute on each of them in some way. In PowerShell, the preferred way of doing that is Invoke-Command. You can try some other method, but it will basically amount to the same idea of executing code on the remote computers.

Test-Connection, for example, appears to let you ping a computer from a remote source via its -Source parameter, but all it’s doing is making a WMI call to that remote computer, and the WMI class then runs the ping. Different protocol, but in principle, the same idea as running Invoke-Command.

On a side note, you don’t have to run Invoke-Command 6000 times. You can run it once, and pass it 6000 computer names or PSSession objects. That will offer you better performance anyway, as Invoke-Command will do some number of the connections in parallel (32 at a time, by default.)

This should do the job:

    # Running this script on Computer A
    $Account = "domain\user-with-eoungh-permissions-on-ComputerB"
    $ComputerB = "ComputerB_Name" # Source computer where we initiate the ip/port check
    $ComputerC = "" # Target computer that we're checking ip/port on
    $Port = 636 # Target port
#    $ComputerC = "" 
#    $Port = 80
    if (!(Test-Path -Path ".\Cred.txt")) {
        Write-Output "Error: missing encrypted pwd file .\Cred.txt, enter the pwd to be encrypted and saved to .\Cred.txt for future script use:" 
        Read-Host 'Enter the pwd to be encrypted and saved to .\Cred.txt for future script use:' -AsSecureString | ConvertFrom-SecureString | Out-File .\Cred.txt
    $Pwd = Get-Content .\Cred.txt | ConvertTo-SecureString 
    $Cred = New-Object System.Management.Automation.PSCredential($Account,$Pwd)
    $ComputerCdata = Invoke-Command -ComputerName $ComputerB -Credential $Cred -ScriptBlock { param($ComputerC,$Port) 
        $socketC = New-object Net.Sockets.TcpClient
        $data = $socketC.Connected
        return $data
    } -ArgumentList $ComputerC,$Port
    if ($ComputerCdata) {Write-Output "Computer $ComputerC socket $Port connected successfully from computer $ComputerB"}
        else {Write-Output "Failed to connect to Computer $ComputerC socket $Port from computer $ComputerB"}