user3001517
user3001517

Reputation: 51

UDP port scanner by using socket php

ok, it's easy to code TCP port scanner by using socket but i don't know why it's hard to be the same for UDP

I just want to check if a specific UDP port (say port 500) is open or not.

Here is my code:

$ip = '103.12.9.209';
$port = '500';

$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);

$result = socket_connect($socket, $ip, $port);

if ($result)
{
    echo "Port is on";
}
else
{
    echo "Port is off";
}

socket_close($socket);

The problem is it always return true (port is on) even it's off.

What is the problem? any idea please?

Thanks.

Upvotes: 1

Views: 1600

Answers (1)

hek2mgl
hek2mgl

Reputation: 157967

You need to send an empty UDP frame to the port in question and check for ICMP responses. If you get ICMP type 2, code 3 (port unreachable) then the port is closed. If you receive other codes like type3, code 1,2,9,10 or 13) the port is filtered. If you receive data or at least don't receive ICMP responses then it can be assumed that the port is open, but however, if there are just no ICMP responses it is not sure that the port is open.

Upvotes: 1

Related Questions