Wojciech Sciesinski
Wojciech Sciesinski

Reputation: 324

How to check local IP address used by system.Net.Sockets.TcpClient?

I would like use code like below

$c = "computername"
$p = PortNumber

#Create object for connecting to port on computer  
$tcpobject = New-Object System.Net.Sockets.TcpClient

#Connect to remote machine's port                
$connect = $tcpobject.BeginConnect($c,$p,$null,$null) 

#Configure a timeout before quitting  
$wait = $connect.AsyncWaitHandle.WaitOne($TCPtimeout,$false)

to test destination port. The code will be run as a part of PowerShell script.

If is it possible to check what local IP address or (at least) local network adapter is used to initiate connection?

Upvotes: 4

Views: 1078

Answers (2)

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239714

Once the connection is established, you can access the TcpClient's Client property, which gives you a Socket that exposes the LocalEndpoint property, that can be cast to an IPEndpoint and interrogated.

But if you want this information before you make the connection, then no. No amount of pre-checking will let you know what state your network connectivity will be in at the later point at which you actually establish the connection.

Upvotes: 2

Andrey Marchuk
Andrey Marchuk

Reputation: 13483

The best I can think of is to check netstat -n -o while you are connected. It will show you the mapping between local and remote address

Upvotes: 0

Related Questions