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

    Question

  • Hi!

    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 IPAddress or (at least) local network adapter is used to initiate connection?

    Thank you in advance for your help.


    Wojciech Sciesinski

    If my answer help you please mark it as the answer or helpful post.

    Thank you.

    Wednesday, May 18, 2016 11:46 AM

Answers

  • Hi it-praktyk,

    Please modify the code as below:

    $Source = @”
    c# code as above
    
    “@ 
    
    Add-Type -ReferencedAssemblies System -TypeDefinition $Source -Language CSharp 
    
     [TcpClientDemo.GetLocalIP]::Get()

    Best regards,

    Cole Wu


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Wednesday, May 25, 2016 8:23 AM

All replies

  • Hi it-praktyk,

    This forum is about general managed code networking topics such as serialization, System.NET, Windows Communication Foundation(WCF), and Web Services, as your issue is more related to powershell, we help you move it to the powershell forum for better support.

    Thank you for your understanding.

    Best regards,

    Cole Wu


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Thursday, May 19, 2016 2:23 AM
  • Thank your for your reply.

    I think that my question is strictly related to .NET so proposal to moving it to PowerShell is not OK for me.


    Wojciech Sciesinski

    If my answer help you please mark it as the answer or helpful post.

    Thank you.

    Thursday, May 19, 2016 12:03 PM
  • Hi it-praktyk,

    According to your description, you want to retrieve local IPAddress, it seems that Tcpclient could achieve it, and I create a simple demo by using c# as below for your reference although this issue is out of our support scope in this forum.

    using System;
    
    using System.Net;
    
    using System.Net.Sockets;
    
    
    namespace TcpClientDemo
    
    {
    
    
        public static class GetLocalIP
    
        {
    
            public static void Get()
    
            {
    
                string host = Dns.GetHostName();
    
                TcpClient client = new TcpClient(host, 80);
    
                Socket s = client.Client;
    
    
                if (!s.Connected)
    
                {
    
                    s.SetSocketOption(SocketOptionLevel.Socket,
    
                                 SocketOptionName.ReceiveBuffer, 16384);
    
                    Console.WriteLine(
    
                        "client is not connected, ReceiveBuffer set\n");
    
                }
    
                else
    
                {
    
                    Console.WriteLine("My local IpAddress is :" + IPAddress.Parse(((IPEndPoint)s.LocalEndPoint).Address.MapToIPv4().ToString()) + "I am connected on port number " + ((IPEndPoint)s.LocalEndPoint).Port.ToString());
    
                }
    
               
    
            }
    
    
           
    
        }
    
    }
    

    Then you could put c# code in your powershell script. Like this:

    $Assem = ( 
        “Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c” , 
        “Microsoft.SharePoint.Publishing, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c” 
        ) 
    
    $Source = @”
    c# code as above
    
    “@ 
    
    Add-Type -ReferencedAssemblies $Assem -TypeDefinition $Source -Language CSharp 
    
     [TcpClientDemo.GetLocalIP]::Get()
    

    For more information, please refer to:

    https://blogs.technet.microsoft.com/stefan_gossner/2010/05/07/using-csharp-c-code-in-powershell-scripts/

    Best regards,

    Cole Wu


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Friday, May 20, 2016 4:07 AM
  • Hi, Wu

    Thank you for proposed answer.

    I encapsulated the code in a separate PowerShell function and added to devel version of the Test-Port function what you can find here https://github.com/it-praktyk/PowerShell_Scripts/blob/devel/Test-Port.ps1

    As the result I receive errors like below. I'm too tired to debug it today.

    [PS] >test-port -computer 192.168.13.22 -port 80
    Add-Type : (0) : Metadata file 'Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral,
    PublicKeyToken=71e9bce111e9429c.dll' could not be found
    (1) : using System;
    At <PATH>\PowerShell_Scripts\Test-Port.ps1:455 char:5
    +     Add-Type -ReferencedAssemblies $Assem -TypeDefinition $Source -La ...
    +     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidData: (error CS0006: M...ld not be found:CompilerError) [Add-Type], Exception
        + FullyQualifiedErrorId : SOURCE_CODE_ERROR,Microsoft.PowerShell.Commands.AddTypeCommand
    
    Add-Type : (0) : Metadata file 'Microsoft.SharePoint.Publishing, Version=14.0.0.0, Culture=neutral,
    PublicKeyToken=71e9bce111e9429c.dll' could not be found
    (1) : using System;
    AT <PATH>\PowerShell_Scripts\Test-Port.ps1:455 char:5
    +     Add-Type -ReferencedAssemblies $Assem -TypeDefinition $Source -La ...
    +     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidData: (error CS0006: M...ld not be found:CompilerError) [Add-Type], Exception
        + FullyQualifiedErrorId : SOURCE_CODE_ERROR,Microsoft.PowerShell.Commands.AddTypeCommand
    
    Add-Type : Cannot add type. Compilation errors occurred.
    At <PATH>\PowerShell_Scripts\Test-Port.ps1:455 char:5
    +     Add-Type -ReferencedAssemblies $Assem -TypeDefinition $Source -La ...
    +     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidData: (:) [Add-Type], InvalidOperationException
        + FullyQualifiedErrorId : COMPILER_ERRORS,Microsoft.PowerShell.Commands.AddTypeCommand
    
    Unable to find type [TcpClientDemo.GetLocalIP].
    At <PATH>\PowerShell_Scripts\Test-Port.ps1:457 char:5
    +     [TcpClientDemo.GetLocalIP]::Get()
    +     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (TcpClientDemo.GetLocalIP:TypeName) [], RuntimeException
        + FullyQualifiedErrorId : TypeNotFound
    
    
    Exception calling "EndConnect" with "1" argument(s): "No connection could be made because the target machine actively
    refused it 192.168.13.22:80"
    At <PATH>\PowerShell_Scripts\Test-Port.ps1:235 char:25
    +                         $tcpobject.EndConnect($connect) | out-Null
    +                         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
        + FullyQualifiedErrorId : SocketException


    Wojciech Sciesinski

    If my answer help you please mark it as the answer or helpful post.

    Thank you.

    Monday, May 23, 2016 9:31 PM
  • Hi it-praktyk,

    Please modify the code as below:

    $Source = @”
    c# code as above
    
    “@ 
    
    Add-Type -ReferencedAssemblies System -TypeDefinition $Source -Language CSharp 
    
     [TcpClientDemo.GetLocalIP]::Get()

    Best regards,

    Cole Wu


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Wednesday, May 25, 2016 8:23 AM