繁体   English   中英

Powershell 脚本监听公共 IP 地址上的 http

[英]Powershell script listen for http on public IP address

我有以下在内部运行良好的代码。 但是,如果我尝试通过公共 IP 地址访问,我会收到“HTTP 错误 400。请求主机名无效。”

$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()

如果我尝试取消对公共 ip 地址行的注释,则会出现大量错误,首先是

使用“0”参数调用“开始”时出现异常:“指定网络名称的格式无效。”

解决方案很简单。 @Mathias R. Jessen 很接近,因为它是通配符。

$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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM