Re: How to select the source ip address for a connection to the database server

From: Bob McConnell <rmcconne(at)lightlink(dot)com>
To: Dimitris Sakellarios <dimitris(dot)sakellarios(at)telesuite(dot)gr>
Cc: pgsql-php(at)postgresql(dot)org
Subject: Re: How to select the source ip address for a connection to the database server
Date: 2009-09-06 19:35:32
Message-ID: 4AA40F04.3020908@lightlink.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-php

Dimitris Sakellarios wrote:
> Bob hi I would be very interested in giving me some small hint of how you
> did that in PERL so I can start from someplace in PHP.
>
> BR.

Well, stripping it down to the basics, here is what I used:

-------------8<------------------------------
$port = 23 unless $port;
$them = 'localhost' unless $them;
$AF_INET = 2;
$SOCK_STREAM = 1;

$sockaddr = 'S n a4 x8';

($name,$aliases,$proto) = getprotobyname('tcp');
($name,$aliases,$port) = getservbyname($port,'tcp')
unless $port =~ /^\d+$/;;
($name,$aliases,$type,$len,$thisaddr) =
gethostbyname($hostname);
($name,$aliases,$type,$len,$thataddr) = gethostbyname($them);

$this = pack($sockaddr, $AF_INET, 0, $thisaddr);
$that = pack($sockaddr, $AF_INET, $port, $thataddr);

if (socket(S, $AF_INET, $SOCK_STREAM, $proto)) {
print "socket ok\n";
}
else {
die $!;
}

if (bind(S, $this)) {
print "bind ok\n";
}
else {
die $!;
}

if (connect(S,$that)) {
print "connect ok\n";
}
else {
die $!;
}
-------------8<------------------------------

The key is the variable $thisaddr. Put your server's DNS name or IP
address as the parameter for the 'gethostbyname($hostname)' call that
initializes it. That binds the outgoing connection to your IP. In my
test platform I use "gethostbyname('10.3.1.70')", which binds it
directly to one of the three network cards in that computer. The rest is
pretty normal for a socket definition.

But as I said, this is pretty low level. It doesn't use any of the
socket libraries or classes most people favor for Perl coding these
days. If you need more ideas, I located this code again today doing a
Google search on "Perl socket bind connect".

Good luck,

Bob McConnell
N2SPP

In response to

Browse pgsql-php by date

  From Date Subject
Next Message Jasen Betts 2009-09-07 10:40:21 Re: How to select the source ip address for a connection to the database server
Previous Message Dimitris Sakellarios 2009-09-06 13:13:26 Re: How to select the source ip address for a connection to the database server