1 #!/usr/perl5/bin/perl -w
5 # The contents of this file are subject to the terms of the
6 # Common Development and Distribution License (the "License").
7 # You may not use this file except in compliance with the License.
9 # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10 # or http://www.opensolaris.org/os/licensing.
11 # See the License for the specific language governing permissions
12 # and limitations under the License.
14 # When distributing Covered Code, include this CDDL HEADER in each
15 # file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16 # If applicable, add the following below this CDDL HEADER, with the
17 # fields enclosed by brackets "[]" replaced with your own identifying
18 # information: Portions Copyright [yyyy] [name of copyright owner]
24 # Copyright 2008 Sun Microsystems, Inc. All rights reserved.
25 # Use is subject to license terms.
29 # get.ipv4remote.pl [tcpport]
31 # Find an IPv4 reachable remote host using both ifconfig(1M) and ping(1M).
32 # If a tcpport is specified, return a host that is also listening on this
33 # TCP port. Print the local address and the remote address, or an
34 # error message if no suitable remote host was found. Exit status is 0 if
41 my $MAXHOSTS = 32; # max hosts to port scan
42 my $TIMEOUT = 3; # connection timeout
43 my $tcpport = @ARGV == 1 ?
$ARGV[0] : 0;
46 # Determine local IP address
52 open IFCONFIG
, '/usr/sbin/ifconfig -a |' or die "Couldn't run ifconfig: $!\n";
56 # "UP" is always printed first (see print_flags() in ifconfig.c):
57 $up = 1 if /^[a-z].*<UP,/;
58 $up = 0 if /^[a-z].*<,/;
60 # assume output is "inet X ... broadcast Z":
61 if (/inet (\S+) .* broadcast (\S+)/) {
62 my ($addr, $bcast) = ($1, $2);
63 $Broadcast{$addr} = $bcast;
64 $local = $addr if $up and $local eq "";
69 die "Could not determine local IP address" if $local eq "";
72 # Find the first remote host that responds to an icmp echo,
73 # which isn't a local address.
75 open PING
, "/usr/sbin/ping -ns $Broadcast{$local} 56 $MAXHOSTS |" or
76 die "Couldn't run ping: $!\n";
78 if (/bytes from (.*): / and not defined $Broadcast{$1}) {
85 my $socket = IO
::Socket
::INET
->new(
100 die "Can't find a remote host for testing: No suitable response from " .
101 "$Broadcast{$local}\n" if $remote eq "";
103 print "$local $remote\n";