How to respond conditionally based on the request when using netcat

我与影子孤独终老i 提交于 2019-11-30 19:41:35

The problem is, as far as I can tell, nc can't perform a callback to tailor its output based on client input. Once you have...

stdout generation | nc -l

... blocking and waiting for a connection, its output is already determined. That output is static at that point.

The only workaround which occurs to me is rather inefficient. It basically involves the following logic:

  1. Listen for a connection prepared to make the client perform a reload
  2. Scrape the GET address from the previous request's headers.
  3. Serve relevant content on client's second connection

Example code:

@echo off & setlocal

rem // macro for netcat command line and args
set "nc=\cygwin64\bin\nc.exe -w 1 -l 80"

rem // macro for sending refresh header
set "refresh=^(echo HTTP/1.1 200 OK^&echo Refresh:0;^)^| %nc%"

for /L %%# in (1,0,2) do (
    rem // run refresh macro and capture client's requested URL
    for /f "tokens=2" %%I in ('%refresh% ^| findstr "^GET"') do set "URL=%%I"

    rem // serve content to the client
    setlocal enabledelayedexpansion
    echo URL: !URL! | %nc%
    endlocal
)

As a side note, delayed expansion can mutilate variable values set with exclamation marks if it's enabled at the time of setting. Best to wait to enable delayed expansion until retrieval.

Also, when performing a boolean check on %ERRORLEVEL% it's more graceful to employ conditional execution. But that has nothing to do with my solution. :)

And finally, instead of doing type filename.html | nc -l, consider using <filename.html nc -l (or nc -l <filename.html) to avoid the useless use of type.

Checkout the -e option, you could write a script that does the processing and then execute

nc -L -w1 -p 80 -eexec.bat

which would pipe stdin and stdout back and forth from nc to the script like you want.

exec.bat could be something like (somewhat pseudo code):

findstr mystring
if not errorlevel 1 (echo found) else (echo not-found)

or maybe a loop (also somewhat pseudo code):

:top
set /p input=
if input wasn't "" echo %input% >> output.dat && goto top
findstr /C:"mystring" output.dat
if not errorlevel 1 (echo found) else (echo not-found)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!