lindseyprog has asked for the wisdom of the Perl Monks concerning the following question:

I have a *IX system with 2 NICs. I have a program that allows me to make a connection to an outside IP address using a socket. This works great except I need to bind to one of my local NICs so that I can go out over the VPN. For example: I have 192.168.199.100 and 200.172.15.40 as my IP addresses for the NICs. The VPN connections ALL use the 192.168.199.100 address but the *IX system will grab whichever NIC is not busy and most of the time it is the 200.172.15.40 address and I can not make a connection to the other side using that address. Without re-writing the code to use more update to date modules does anyone know of a way to get "use Socket"; to bind to a LOCAL IP address. Below is my "connecting" code that the program currently uses.
$them = $opt_h; $iaddr = inet_aton($remote); $paddr = sockaddr_in($port, $iaddr); $proto = getprotobyname('tcp'); socket(SOCKET, AF_INET, SOCK_STREAM, $proto) || die "socket error: + $!"; print STDOUT "connecting...\n\n"; if (connect(SOCKET,$paddr)) { print STDOUT "Connected to host: $them, port: $port\n\n"; } else { die "socket error: $!"; }

Replies are listed 'Best First'.
Re: bind a client connection
by wrog (Friar) on Feb 11, 2012 at 21:22 UTC
    you can use bind() on outgoing connections, e.g.,

    bind(SOCKET, pack_sockaddr_in(0, inet_aton($local_ip)))

    It's exactly the same as when you're setting up a server except that you're calling connect rather than listen

    (... and the point of using pack_sockaddr_in is so that you don't have to create extra variables you don't need. Unlike with sockaddr_in which looks at its context to see whether it should be packing or unpacking, pack_sockaddr_in always packs... and you could do that with the connect() call as well to get rid of $iaddr and $paddr...)

        Without re-writing the code to use more [up] to date modules
Re: bind a client connection
by Anonymous Monk on Feb 10, 2012 at 21:23 UTC
    That ought to work, provided $remove/$iaddr/$paddr contains the IP you want (192.168.199.100)