1#!/usr/local/bin/perl -w
2### discover
3### Author:	  Simon Leinen <simon@switch.ch>
4### Date Created: 1998-Oct-16
5###
6### discover ADDRESS [COMMUNITY]
7###
8### Send a specific SNMP request to a IP address and wait for replies.
9### Can be used with a broadcast or multicast address to discover SNMP
10### agents ("Command Responder Applications") responding to a given
11### community.  Warning: This code uses internal subroutines of the
12### SNMP_Session.pm module which are subject to change :-(
13###
14use strict;
15use vars qw($MULTILINE_MATCHING);
16
17require 5;
18
19use SNMP_Session "0.61";
20use BER;
21use Socket;
22
23my $host = shift @ARGV || die;
24my $community = shift @ARGV || 'public';
25
26my $sysDescr = encode_oid (1,3,6,1,2,1,1,1,0);
27
28my $session = SNMP_Session->open ($host, $community, 161)
29    || die "Cannot open SNMP session";
30my @oids = ($sysDescr);
31$session->send_query ($session->encode_get_request (@oids));
32while ($session->wait_for_response ($session->timeout)) {
33    my($response_length);
34
35    $response_length
36	= $session->receive_response_3 (SNMP_Session::get_response, \@oids, 0);
37    if ($response_length) {
38	my $response = $session->pdu_buffer;
39	my ($binding, $bindings, $oid, $value);
40	eval {
41	    ($bindings) = $session->decode_get_response ($response);
42	};
43	while ($bindings ne '') {
44	    ($binding,$bindings) = decode_sequence ($bindings);
45	    ($oid,$value) = decode_by_template ($binding, "%O%@");
46	    ##print $pretty_oids{$oid}," => ",
47	    {
48		my $string = pretty_print ($value);
49		my $sender = $session->{'last_sender_addr'};
50		local $MULTILINE_MATCHING = 1;
51		$string =~ s/\n/\\n/g;
52		$string =~ s/\r/\\r/g;
53		print STDOUT pretty_address ($sender), "\n  ";
54		print STDOUT $string, "\n";
55	    }
56	}
57    }
58}
59
60$session->close ();
611;
62
63sub pretty_address
64{
65    my($addr) = shift;
66    my($port,$ipaddr) = unpack_sockaddr_in($addr);
67    my $hostname = gethostbyaddr ($ipaddr, AF_INET);
68    return $hostname ? $hostname : ('['.inet_ntoa($ipaddr).']');
69}
70