1

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?

4

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.

  • 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? – rainereality Sep 18 '14 at 23:12
  • 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 – rainereality Sep 19 '14 at 2:56
  • 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. – rainereality Sep 19 '14 at 2:57
4

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

telnet server port

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.