pingではポート番号の確認ができない
ネットワークの疎通確認でpingを行うことがよくあると思います。しかし通信先が最近のWindows環境の場合、ファイアウォールがデフォルトでpingの受信を遮断するという設定になっています。このためpingが失敗した原因がファイアウォールなのかネットワーク環境なのか判断できないなんてこともありますよね。
また、Webサイト等を構築している際にはWebサーバーに繋がるか、DBに繋がるかを調べたい時にはIPアドレスとポート番号セットで確認したいですよね。PowerShellのコマンドでポート番号も含めて確認を行うことができます。
Test-Connectionコマンド
PowerShellのバージョンが7.0以上であれば「Test-Connection」コマンドで確認可能です。非常に高速に動作する疎通確認で、実行結果はTrue(=疎通可能) / False(疎通不可)で返ってきます。公式ドキュメントによると下記のような構文のようです。
Test-Connection > TcpPort
Test-Connectionhttps://learn.microsoft.com/ja-jp/powershell/module/microsoft.powershell.management/test-connection?view=powershell-7.5#tcpport
[-TargetName] <string[]>
-TcpPort <int>
[-IPv4]
[-IPv6]
[-ResolveDestination]
[-Source <string>]
[-Count <int>]
[-Delay <int>]
[-Repeat]
[-Quiet]
[-TimeoutSeconds <int>]
[-Detailed]
[<CommonParameters>]
実際に実行してみると下記のような形となります。
疎通OKの場合
PowerShell
PS > Test-Connection 127.0.0.1 -TcpPort 8080
True
疎通NGの場合
PowerShell
PS > Test-Connection 127.0.0.1 -TcpPort 12345
False
Test-NetConnectionコマンド
PowerShellのバージョンが7.0以上が使用できない環境、またはもう少し詳細な確認を行いたい場合「Test-NetConnection」を使うことができます。こちらはTest-Connectionより若干実行に時間がかかります。
こちらも公式ドキュメントによると下記のような構文のようです。
Test-NetConnection > RemotePort
Test-NetConnectionhttps://learn.microsoft.com/ja-jp/powershell/module/nettcpip/test-netconnection?view=windowsserver2025-ps#remoteport
[[-ComputerName] <String>]
-Port <Int32>
[-InformationLevel <String>]
[[<CommonParameters>]]
実際に実行してみると下記のような形となります。
疎通OKの場合
PowerShell
PS > Test-NetConnection 127.0.0.1 -Port 8080
ComputerName : 127.0.0.1
RemoteAddress : 127.0.0.1
RemotePort : 8080
InterfaceAlias : Loopback Pseudo-Interface 1
SourceAddress : 127.0.0.1
TcpTestSucceeded : True
疎通NGの場合
PowerShell
PS > Test-NetConnection 127.0.0.1 -Port 12345
WARNING: TCP connect to (127.0.0.1 : 12345) failed
ComputerName : 127.0.0.1
RemoteAddress : 127.0.0.1
RemotePort : 12345
InterfaceAlias : Loopback Pseudo-Interface 1
SourceAddress : 127.0.0.1
PingSucceeded : True
PingReplyDetails (RTT) : 0 ms
TcpTestSucceeded : False



コメント