Skip to content

Instantly share code, notes, and snippets.

@jplitza
Created February 23, 2024 14:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jplitza/196d2aca7e80b5b092a023aa12f98063 to your computer and use it in GitHub Desktop.
Save jplitza/196d2aca7e80b5b092a023aa12f98063 to your computer and use it in GitHub Desktop.
Netcat in Bash
#!/bin/bash
set -eu
PROXY=false
usage() {
echo "Usage: $0 [-X connect -x <proxy:port>] <host> <port>"
}
while getopts ":X:x:" OPT; do
case "$OPT" in
X)
if [[ "$OPTARG" != "connect" ]]; then
echo "Unsupported argument to -X: ${OPTARG}" >&2
usage
exit 1
fi
PROXY=true
;;
x)
PROXY_HOST="${OPTARG%:*}"
PROXY_PORT="${OPTARG#*:}"
;;
?)
usage
exit 0
;;
esac
done
shift $((OPTIND-1))
if [[ "$#" != 2 ]]; then
echo "No host/port given" >&2
usage
exit 1
fi
HOST="$1"
PORT="$2"
if $PROXY; then
if [[ -z "$PROXY_HOST" || -z "$PROXY_PORT" ]]; then
echo '"-X connect" given without -x proxy:port' >&2
usage
exit 1
fi
printf -v PROXIED "%s:%d" "$HOST" "$PORT"
HOST="$PROXY_HOST"
PORT="$PROXY_PORT"
fi
exec 3<> "/dev/tcp/${HOST}/${PORT}"
if $PROXY; then
printf "CONNECT %s HTTP/1.1\r\nHost: %s\r\n\r\n" "$PROXIED" "$PROXIED" >&3
read -u 3 -r LINE
if [[ "$LINE" != "HTTP/1.1 200 Connection established"$'\r' ]]; then
echo "Connecting to proxy failed" >&2
exit 1
fi
fi
cat <&3 &
READER=$!
cat >&3
kill $READER 2>/dev/null
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment