Send Text String to a Socket In Windows

19,608

Solution 1

Here's a little Powershell for you... should be compatible with any version of PS... maybe PSv2 or better. Works with either host names or IP addresses.

Function Send-StringOverTcp ( 
    [Parameter(Mandatory=$True)][String]$DataToSend,
    [Parameter(Mandatory=$True)][String]$Hostname, 
    [Parameter(Mandatory=$True)][UInt16]$Port)
{
    Try
    {
        $ErrorActionPreference = "Stop"
        $TCPClient  = New-Object Net.Sockets.TcpClient
        $IPEndpoint = New-Object Net.IPEndPoint($([Net.Dns]::GetHostEntry($Hostname)).AddressList[0], $Port)
        $TCPClient.Connect($IPEndpoint)
        $NetStream  = $TCPClient.GetStream()
        [Byte[]]$Buffer = [Text.Encoding]::ASCII.GetBytes($DataToSend)
        $NetStream.Write($Buffer, 0, $Buffer.Length)
        $NetStream.Flush()
    }
    Finally
    {
        If ($NetStream) { $NetStream.Dispose() }
        If ($TCPClient) { $TCPClient.Dispose() }
    }
}

    Send-StringOverTcp -DataToSend 'foo!' -Hostname google.com -Port 80

I wrote this very hastily... you might want to put extra parameter validation and error trapping in there, but you get the idea. Also worth considering is that Windows uses UTF16 LE encoding by default, so characters are typically "wide," as opposed to many other systems which use narrow characters. So you may want to encode the string as Unicode instead of ASCII, etc. Depends on what you're using it for.

Or if you'd rather make it as simple as your Netcat example, just... download Netcat for Windows.

Solution 2

you can use PuTTY for this, select the raw connection option. Telnet may also work for you

telnet server port

Share:
19,608

Related videos on Youtube

cheesesticksricepuck
Author by

cheesesticksricepuck

Updated on September 18, 2022

Comments

  • cheesesticksricepuck
    cheesesticksricepuck over 1 year

    I have a server that has an open socket that listens for a particular text string on it in order to perform an action.

    Our linux machines send this data via:

    echo "text_string" | nc -w 2 server-name port#
    

    Is this possible on Windows (possibly in powershell or other builtin utilities)? If so, how?

  • cheesesticksricepuck
    cheesesticksricepuck over 9 years
    If I download netcat for windows. How do I "pipe" the output from powershell to the application? I can't really go write "output" | netcat.exe <options> can I?
  • cheesesticksricepuck
    cheesesticksricepuck over 9 years
    Nevermind apparently pipelining works in Windows. I guess my Windows skills need some work. PS C:\Users\root> Write TPC-F11-21-021 | ncat.exe -w 2 10.128.0.20 2069 ERROR unrecognized command close: No error
  • cheesesticksricepuck
    cheesesticksricepuck over 9 years
    Ryan, thanks for the response I'll be attempting your method in a few days. For now I will be using netcat for windows but I would like to not have to.