Skip to content
Advertisement

Using netcat to issue a http get request in bash

I have written the following script (it does not support index yet). The issue I am having is regarding using netcat to load the page. I can do this manually using the command line but when I try to have my script issue the exact same commands I can it does nothing without error. The only possible thing I can think is that my output is going somewhere else?

#!/bin/bash
PORT=80

while [ true ]
do
    echo "Type the address you wish to visit then, followed by [ENTER]:"
    read address
    path=${address#*/}
    domain=${address%%/*}
    nc $domain $PORT
    printf "GET /$path HTTP/1.1n" 
    printf "Host: $domainn" 
    printf "n" 
    printf "n" 
done

Advertisement

Answer

nc works by copying standard input to the given address:port, and copying whatever it reads from there to standard output.

{
  printf "GET /%s HTTP/1.1rn" "$path"
  printf "Host: %srn" "$domain"
  printf "rn" 
  printf "rn"
} | nc "$domain" "$port"
  • HTTP requires rn at the end of each line. Some servers accept just n but some stick to the letter of the law and accept only rn as specified.

  • You need to send these lines to the standard input of nc.

  • It is better to use printf "Get %s HTTP/1.1rn" "$path" because$pathmay contain%signs and that would confuseprintf`.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement