The CGI program is typically not directly connected to the client socket in any way, so
getpeername() is unlikely to work. The correct solution is to tell Apache to provide the
REMOTE_PORT environment variable for you.
The simplest method I can think of is to enable URL rewriting via the
mod_rewrite module: add
Code:
RewriteEngine On
Options +FollowSymlinks
RewriteCond (%{REMOTE_PORT}) ^
RewriteRule ^ - [E=REMOTE_PORT:%1]
to the Directory section that governs your CGI scripts in your Apache configuration.
The way this works is that the URL rewriting engine knows about the remote port; it refers to it as
%{REMOTE_PORT}. Since it is in parentheses, it will be accessible in any applied rule using %1. Since every string has a start, the condition always matches. The rule always matches also. The
- tells the rule to do no replacements. The
[E=REMOTE_PORT:%1] sets the REMOTE_PORT environment variable as per the remote port. For the rewrite engine to work, both RewriteEngine and symlinks (FollowSymlinks or SymlinksIfOwnerMatch) must be enabled.