Skip to content

Instantly share code, notes, and snippets.

@Javlopez
Created May 15, 2013 22:42
Show Gist options
  • Save Javlopez/5588014 to your computer and use it in GitHub Desktop.
Save Javlopez/5588014 to your computer and use it in GitHub Desktop.
Example functional of sockets
<?php
error_reporting(E_ALL);
/* Get the port for the WWW service. */
$service_port = getservbyname('www', 'tcp');
/* Get the IP address for the target host. */
$address = gethostbyname('www.google.com');
/* Create a TCP/IP socket. */
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
echo "socket_create() failed: reason: " .
socket_strerror(socket_last_error()) . "\n";
}
echo "Attempting to connect to '$address' on port '$service_port'...";
$result = socket_connect($socket, $address, $service_port);
if ($result === false) {
echo "socket_connect() failed.\nReason: ($result) " .
socket_strerror(socket_last_error($socket)) . "\n";
}
$in = "HEAD / HTTP/1.1\r\n";
$in .= "Host: www.google.com\r\n";
$in .= "Connection: Close\r\n\r\n";
$out = '';
echo "Sending HTTP HEAD request...";
socket_write($socket, $in, strlen($in));
echo "OK.\n";
echo "Reading response:\n\n";
while ($out = socket_read($socket, 2048)) {
echo $out;
}
socket_close($socket);
?>
@Javlopez
Copy link
Author

Add the response

/www/server $ php socket.php
Attempting to connect to '74.125.227.211' on port '80'...Sending HTTP HEAD request...OK.
Reading response:

HTTP/1.1 302 Found
Location: http://www.google.com.mx/
Cache-Control: private
Content-Type: text/html; charset=UTF-8
Set-Cookie: PREF=ID=1a5476021af02141:FF=0:TM=1368656572:LM=1368656572:S=3W66-2u8LnwRMHsZ; expires=Fri, 15-May-2015 22:22:52 GMT; path=/; domain=.google.com
Set-Cookie: NID=67=qfcUb0rVkco1zQDd8c3G8MKAqYFTEqdYaGlq6nxmqJpoP3YuWu3yZHZKXbpi3I1XMhQPjI1E5Mq3urXd0diMu1d716ijy49WrlbFGN-gX4Ds-7L6qOFwkaorp8OEUWUX; expires=Thu, 14-Nov-2013 22:22:52 GMT; path=/; domain=.google.com; HttpOnly
P3P: CP="This is not a P3P policy! See http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657 for more info."
Date: Wed, 15 May 2013 22:22:52 GMT
Server: gws
Content-Length: 222
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN
Connection: close

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment