Archive for August, 2008

Binding PHP’s fsockopen to a specific IP address

Thursday, August 21st, 2008

Suppose you use PHP’s fsockopen method in your code. For example you want to send POST requests to a remote server. Chances are you’ve got something like this:

  1. $socket = @fsockopen('ssl://xmlapi.example.org' , 9090 , $errno , $errstr , 30);

There is nothing wrong with this code, but if your web server listens to multiple IP addresses, you might not be happy with the default IP used for the outgoing connection to the remote server. In this case you might want to specify the IP address, that is used by PHP to send the request.

Alright, the title of the post is a bit misleading. Actually, you can’t bind sockets opened with fsockopen to a specific IP address. But you can use the methods stream_context_create and stream_socket_client to open a socket that can be used equal to a socket opened by fsockopen. You can use the ressource handle $socket returned by stream_socket_client like a source handle returned by fsockopen. The drawback is, that these methods are only available since PHP version 5. But as PHP version 4 is no longer supported by the PHP team, you should switch anyway, if you haven’t already.

The following code tests, if the methods in question are supported by your PHP installation. If so, they bind the socket to the IP address 192.0.2.1. :0 means, that we do not care about the outgoing port number used by the socket. You could specify a specific port here, too.

  1. if (function_exists('stream_context_create') && function_exists('stream_socket_client')) {
  2. $socket_options = array('socket' => array('bindto' => '192.0.2.1:0'));
  3. $socket_context = stream_context_create($socket_options);
  4. $socket = stream_socket_client('ssl://xmlapi.example.org:9090', $errno,
  5. $errstr, 30, STREAM_CLIENT_CONNECT, $socket_context);
  6. } else {
  7. $socket = @fsockopen( "ssl://xmlapi.example.org" , 9090 , $errno , $errstr , 30 );
  8. }

The only requirement is, that your web server is configured to listen to the IP you want to bind the socket to. If you specify a specific port number, the port number must not be used by another service. It must be a port above 1024 also. Unless your web server runs as root, which would be a big security problem.

Deep Sea Diving

Sunday, August 10th, 2008

(My) cabinets are like the deep sea. You don’t really know what’s in there and you’ll find something interesting once in a while. I just found another 5 DM bank note in one of them. To be honest, I didn’t remember that a bank note with a 5 DM denomination ever existed. I just remember 5 DM coins. On one side is Bettina von Arnim, on the other side is the Brandenburg gate.

5 DM bank note (front)

I also found a 1 Pfennig coin and three 1 Escudo coins.

5 DM bank note (back)

I guess I need to visit the building with the elevator usability issues once more.