Checking For Open Ports
9
This is a simple PHP script that will show whether a certain port/socket of a certain computer is currently open/active.
<?php
/*First, a variable must be used to store socket_create(). This will tell PHP the protocols and different settings that will be used to connect. For more information on this function, I would advise that you look at the PHP manual. I really didn't get too into this function, I just used some trial and error to find out what would work best. For those who do not know, the @ in front of the function prevents errors that might occur from showing. If you are having trouble with this script, it is suggested that you take the @ out.*/
//PC: $sock = @socket_create (<domain>, <type>, <protocol>);
$sock = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
/*This next variable is the actual connection. The function socket_connect() will attempt to connect to the IP address. I am not sure if you can use domains in this field or not. After the IP address comes the port number that you are trying to get the status of. [Just so you all know ahead of time, socket_connect() will return an integer!] In this case, the script will check your localhost to see if the default http port (80) is open.*/
//PC: $sock2 = @socket_connect($sock, "<ip address>", <port/socket>);
$sock2= @socket_connect($sock,"127.0.0.1", 80);
/*These if and else if statements will compare the number that was recieved from the socket_connect() function with other numbers to return their status. In this instance, I made the script echo the status to be user friendly instead of the numbers 1, 2, or 3. I do not thing that pseudo code is really needed here. All you need to know is the integers that you get back from $sock2:
0: Connection timeout. This usually means that the port is open, but the program that usually uses it is not properly functioning. This is not always the case, just so you know, but this is the common case for me.
1: The port is open and accepting connections (presumably).
2: The connection was refused. That may mean that the port is closed.*/
if($sock2==0) {
echo "Down! (Timeout)";
}
else if($sock2==1) {
echo "Up!";
}
else if($sock2==2) {
echo "Down! (Refused)";
}
/*If you get any data that does not seem right, you will get the error. The only numbers that I know that you can get if you do this correctly is 1, 2, and 3. Any others most likely means that you did something wrong with the variables.*/
else {
echo "Unknown error...";
}
/*Now that everything has been executed, we no longer need to connection so it is dropped! The end!*/
socket_close($sock);
?>
For reference, explinations will be put in /**/ comment tags. Pseudo code will be put after // comment tags. Usually, the pseudo code is from the PHP manual.
I hope that this is helpful!






There are currently no comments for this snippet.