PHP SOCKS4 Interface


SOCKS was originally developed by David Koblas and subsequently modified and extended by me to its current running version — version 4. It is a protocol that relays TCP sessions at a firewall host to allow application users transparent access across the firewall. Because the protocol is independent of application protocols, it can be (and has been) used for many different services, such as telnet, ftp, finger, whois, gopher, WWW, etc. Access control can be applied at the beginning of each TCP session; thereafter the server simply relays the data between the client and the application server, incurring minimum processing overhead. Since SOCKS never has to know anything about the application protocol, it should also be easy for it to accommodate applications which use encryption to protect their traffic from nosey snoopers.

( Reference: http://www.openssh.org/txt/socks4.protocol )

Here is a quick function I threw together for using a Socks4 proxy from PHP.

function fsocks4sockopen($proxyHostname, $proxyPort, $targetHostname, $targetPort)
{
    $sock = fsockopen($proxyHostname, $proxyPort);
    if ($sock === false)
        return false;
    $ip = gethostbyname($targetHostname);
    if (preg_match('/(\d+)\.(\d+)\.(\d+)\.(\d+)/', $ip, $matches))
        $int = pack('C4', $matches[1], $matches[2], $matches[3], $matches[4]);
    else {
        fclose($sock);
        return false;
    }
    $request = pack('C2', 0x04, 0x01) . pack('n', $targetPort) . $int . '0' . pack('C',
        0x00);
    fwrite($sock, $request);
    $resp = fread($sock, 9);
    if (strlen($resp) != 8) {
        fclose($sock);
        return false;
    }
    $answer = unpack('Cvn/Ccd', substr($resp, 0, 2));
    if ($answer['vn'] != 0x00 && $answer['vn'] != 0x04) {
        fclose($sock);
        return false;
    }
    if ($answer['cd'] != 0x5A) {
        fclose($sock);
        return false;
    }
    return $sock;
}

Example usage:

$sock = fsocks4sockopen('199.127.98.31','1080','2tuts.com','80');

if(!$sock) die('error');

$packet = "GET / HTTP/1.1
Host: 2tuts.com
Content-Type: application/x-www-form-urlencoded
User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:8.0.1) Gecko/20100101 Firefox/8.0.1
Connection: close

";

fwrite($sock,$packet);

$res = '';
while(!feof($sock)){
    $res .= fgets($sock,4096);
}

echo $res;