1#!/usr/perl5/bin/perl -w 2# 3# CDDL HEADER START 4# 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. 8# 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. 13# 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] 19# 20# CDDL HEADER END 21# 22 23# 24# Copyright 2008 Sun Microsystems, Inc. All rights reserved. 25# Use is subject to license terms. 26# 27 28# 29# get.ipv4remote.pl [tcpport] 30# 31# Find an IPv4 reachable remote host using both ifconfig(8) and ping(8). 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 35# a host was found. 36# 37 38use strict; 39use IO::Socket; 40 41my $MAXHOSTS = 32; # max hosts to port scan 42my $TIMEOUT = 3; # connection timeout 43my $tcpport = @ARGV == 1 ? $ARGV[0] : 0; 44 45# 46# Determine local IP address 47# 48my $local = ""; 49my $remote = ""; 50my %Broadcast; 51my $up; 52open IFCONFIG, '/usr/sbin/ifconfig -a |' or die "Couldn't run ifconfig: $!\n"; 53while (<IFCONFIG>) { 54 next if /^lo/; 55 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].*<,/; 59 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 ""; 65 $up = 0; 66 } 67} 68close IFCONFIG; 69die "Could not determine local IP address" if $local eq ""; 70 71# 72# Find the first remote host that responds to an icmp echo, 73# which isn't a local address. 74# 75open PING, "/usr/sbin/ping -ns $Broadcast{$local} 56 $MAXHOSTS |" or 76 die "Couldn't run ping: $!\n"; 77while (<PING>) { 78 if (/bytes from (.*): / and not defined $Broadcast{$1}) { 79 my $addr = $1; 80 81 if ($tcpport != 0) { 82 # 83 # Test TCP 84 # 85 my $socket = IO::Socket::INET->new( 86 Proto => "tcp", 87 PeerAddr => $addr, 88 PeerPort => $tcpport, 89 Timeout => $TIMEOUT, 90 ); 91 next unless $socket; 92 close $socket; 93 } 94 95 $remote = $addr; 96 last; 97 } 98} 99close PING; 100die "Can't find a remote host for testing: No suitable response from " . 101 "$Broadcast{$local}\n" if $remote eq ""; 102 103print "$local $remote\n"; 104