tags:

views:

68

answers:

3
// Create a new socket
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

// An example list of IP addresses owned by the computer
$sourceips['kevin']    = '127.0.0.1';
$sourceips['madcoder'] = '127.0.0.2';

// Bind the source address
socket_bind($sock, $sourceips['madcoder']);

// Connect to destination address
socket_connect($sock, $sourceips['madcoder'], 80);

// Write
$request = 'GET / HTTP/1.1' . "\r\n" .
  'Host: example.com' . "\r\n\r\n";
socket_write($sock, $request);

// Close
socket_close($sock);

I am getting an error

Warning: socket_connect() [function.socket-connect]: unable to connect [0]: A socket operation was attempted to an unreachable host. in C:\wamp\www\sockert\sockert.php on line 13

Thanks,

+1  A: 

Hmm, looks like you took this example straight from the PHP reference page for socket_bind(). I'm assuming that, in addition, you didn't change any of the code, and don't have a machine set at 127.0.0.2. This is your problem.

Remember, example code is just example code. Here's a working example based on the example code that looks at a random google IP. I've added the socket_read() function as well so you can see a bit of the data (well, 1024 bytes of it) that you get back.

    <?php
    // Create a new socket
    $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

    // An example list of IP addresses owned by the computer
    $sourceips['google'] = '74.125.127.103';

    // Bind the source address
    socket_bind($sock, $sourceips['google']);

    // Connect to destination address
    socket_connect($sock, $sourceips['google'], 80);

    // Write
    $request = 'GET / HTTP/1.1' . "\r\n" .
               'Host: google.com' . "\r\n\r\n";
    socket_write($sock, $request);

    // You'll get some HTTP header information here,
    // and maybe a bit of HTML for fun!
    print socket_read($sock, 1024);

    // Close
    socket_close($sock);
    ?>
Owen
+1  A: 

Is your development system actually listening to 127.0.0.2? Generally they only listen to 127.0.0.1 as the loopback address.

You can get a list of active listening IPs/ports with netstat -a -p tcp

Marc B
A: 

It means there is no port 80 on 127.0.0.2. Are you expecting to connect to a web server?

ping 127.0.0.2

If you get no response, you will need to point to a new address.

cdburgess