#!/usr/local/bin/perl -s
# chkmail - check an email address
#
# Rob Funk <funk+@osu.edu> 05-Oct-1995

sub AF_INET { 2; };

if ($#ARGV < 0) { # no arguments
   print "usage:\n  $0 [-v] user\@host [user\@host ...]\n";
   exit(0);
}

while ($_=shift) { # do all this for each address given on the command line
    @addr = split(/@/); # separate address
    $user = $addr[0];
    $addr[1] = ($addr[1] || "localhost");
    $host = (gethostbyname($addr[1]))[0] || die("Host unknown\n");
    print "Checking: $user\@$host\n" if ($v);

    $PORT = 25; # SMTP port
    $sockaddr = "Snc4x8"; # BSD sockets
    $there = pack($sockaddr,&AF_INET,$PORT,&getaddress($host));
    die "socket: $!\n" if (!socket(S,&AF_INET,1,6));
    die "connect: $!\n" if (!connect(S,$there));

    select(S); $| = 1;
    select(STDOUT); $| = 1; # make unbuffered

    #$SHOWIT = $v;
    while (read(S,$c,1)) {	# get a character
	if ($c eq "\n") {
	    if (($curline !~ /^220/) || $v) {
	        $tmp = $curline;
		# get rid of status at beginning
		$tmp =~ /^(\d\d\d)/; $result=$1;
		$tmp =~ s/^\d\d\d // if (! $v);
		print "$tmp\n";
		$tmp = "";
	    }
	    if ($curline =~ /^220/) {	# first prompt, Ready
	        # SMTP Verify command
		$who = "$user\@$host";
		#$who = "$user";
		print S "VRFY <$who>\n";
		print "VRFY <$who>\n" if ($v);
		$who="";
		#$SHOWIT = 1;
	    } else {	# close connection
		close S;
		next;
	    }
	    $curline = "";
	    next;
	}
	if ($c eq "\r") { next; } # ignore carriage returns
	$curline .= $c;
    }
    $curline = "";
}

exit($result-250); # 250 means complete success, so return 0 in that case

# get IP array for host
sub getaddress {
    local($host) = @_[0];
    local($addr);
    $addr = (gethostbyname($host))[4];
    return(unpack("C4",$addr))
}
