0

I have the following code that works great internally. However, if I try to access via the public IP address I get "HTTP Error 400. The request hostname is invalid."

$httpListener = New-Object System.Net.HttpListener
$httpListener.Prefixes.Add("http://localhost:5000/")
$httpListener.Prefixes.Add("http://127.0.0.1:5000/")
#$httpListener.Prefixes.Add("http://publicipaddress:5000/")
$httpListener.Start()
write-host "Listening..."
do { 
    $context = $httpListener.GetContext() 
    $context.Response.StatusCode = 200 
    $context.Response.ContentType = 'text/HTML' 
    $WebContent = Get-Content -Path "C:\fusion\scott\test.html" -Encoding UTF8 
    $EncodingWebContent = [Text.Encoding]::UTF8.GetBytes($WebContent) 
    $context.Response.OutputStream.Write($EncodingWebContent , 0, $EncodingWebContent.Length) 
    $context.Response.Close() 
    Write-Host "." -NoNewLine
} until ([System.Console]::KeyAvailable)
$httpListener.Close()

If I try to uncomment the public ip address line, I then get tons of errors, starting with

Exception calling "Start" with "0" argument(s): "The format of the specified network name is invalid."

  • Try adding trailing wildcards to the path prefixes: eg. `"http://localhost:5000/*"` – Mathias R. Jessen Dec 20 '22 at 15:52
  • Make sure you have a route to machine. From cmd.exe on client >Pint IP (or hostname). Use Ping to test route. Try both IP and computer name. You need to get ping working before trying http. – jdweng Dec 20 '22 at 16:19
  • Are you running as administrator? If not, you may need to allow access to that URL like https://stackoverflow.com/a/4115328/7411885 . If you do have access, then make sure your system is listening on that IP as well with `netsh http show iplisten` https://stackoverflow.com/a/47969830/7411885 – Cpt.Whale Dec 20 '22 at 16:55
  • @MathiasR.Jessen: `Only Uri prefixes ending in '/' are allowed` –  Dec 20 '22 at 18:12

1 Answers1

0

The solution was simple. @Mathias R. Jessen was close, as it is a wildcard.

$httpListener = New-Object System.Net.HttpListener
$httpListener.Prefixes.Add("http://*:5000/")
$httpListener.Start()
write-host "Listening..."
do { 
    $context = $httpListener.GetContext() 
    $context.Response.StatusCode = 200 
    $context.Response.ContentType = 'text/HTML' 
    $WebContent = Get-Content -Path "C:\fusion\scott\test.html" -Encoding UTF8 
    $EncodingWebContent = [Text.Encoding]::UTF8.GetBytes($WebContent) 
    $context.Response.OutputStream.Write($EncodingWebContent , 0, $EncodingWebContent.Length) 
    $context.Response.Close() 
    Write-Host "." -NoNewLine
} until ([System.Console]::KeyAvailable)
$httpListener.Close()