PHP Socket Client


SUBMITTED BY: chrischenai

DATE: Oct. 18, 2017, 7:40 p.m.

FORMAT: PHP

SIZE: 1.2 kB

HITS: 313

  1. <?php
  2. error_reporting(E_ALL);
  3. echo "<h2>TCP/IP Connection</h2>\n";
  4. /* Get the port for the WWW service. */
  5. $service_port = getservbyname('www', 'tcp');
  6. /* Get the IP address for the target host. */
  7. $address = gethostbyname('www.example.com');
  8. /* Create a TCP/IP socket. */
  9. $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
  10. if ($socket === false) {
  11. echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
  12. } else {
  13. echo "OK.\n";
  14. }
  15. echo "Attempting to connect to '$address' on port '$service_port'...";
  16. $result = socket_connect($socket, $address, $service_port);
  17. if ($result === false) {
  18. echo "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
  19. } else {
  20. echo "OK.\n";
  21. }
  22. $in = "HEAD / HTTP/1.1\r\n";
  23. $in .= "Host: www.example.com\r\n";
  24. $in .= "Connection: Close\r\n\r\n";
  25. $out = '';
  26. echo "Sending HTTP HEAD request...";
  27. socket_write($socket, $in, strlen($in));
  28. echo "OK.\n";
  29. echo "Reading response:\n\n";
  30. while ($out = socket_read($socket, 2048)) {
  31. echo $out;
  32. }
  33. echo "Closing socket...";
  34. socket_close($socket);
  35. echo "OK.\n\n";
  36. ?>

comments powered by Disqus