[comp.lang.perl] Closing down a connected network socket

worley@compass.com (Dale Worley) (09/29/90)

I'm trying to build a client that connects in sequence to several
different servers.  In order to not have to call socket and bind
repeatedly, I want to just connect to each server and then do shutdown
to disconnect.  However, I'm having trouble getting it to work -- no
value of the HOW parameter seems to leave the socket in a clean state
that can execute a further connect without error.

I don't know what I'm doing wrong.  Has anybody done this who can tell
me what the correct method is?

Dale Worley		Compass, Inc.			worley@compass.com
--
I don't practice what I preach, because I'm not the sort of person I'm 
preaching *to*.  -- J. R. Dobbs

The code I'm using is:

#! /usr/local/bin/perl

$port = 11009;

@remotes = ('sn1987a', 'zeppelin', 'solen');

do '/compass/c/worley/perl-3.0/sys/socket.h' || die "Can't do sys/socket.h: $@";

$sockaddr = 'S n a4 x8';
chop($hostname = `hostname`);

($name, $aliases, $proto) = getprotobyname('tcp');
($name, $aliases, $port) = getservbyname($port, 'tcp')
     unless $port =~ /^\d+$/;
($name, $aliases, $type, $len, $thisaddr) =
		    gethostbyname($hostname);

$this = pack($sockaddr, &AF_INET, 0, $thisaddr);

socket(S, &PF_INET, &SOCK_STREAM, $proto) || die "socket: $!";
bind(S, $this) || die "bind: $!";
select(S); $| = 1; select(stdout);

foreach $remote (@remotes) {
	($name, $aliases, $type, $len, $thataddr) = gethostbyname($remote);
	$that = pack($sockaddr, &AF_INET, $port, $thataddr);

	connect(S, $that) || die "connect: $!";
	print <S>;

	shutdown(S, 2) || die "shutdown: $!";
}

lwall@jpl-devvax.JPL.NASA.GOV (Larry Wall) (09/29/90)

In article <1990Sep28.214349.18443@uvaarpa.Virginia.EDU> worley@compass.com writes:
: I'm trying to build a client that connects in sequence to several
: different servers.  In order to not have to call socket and bind
: repeatedly, I want to just connect to each server and then do shutdown
: to disconnect.  However, I'm having trouble getting it to work -- no
: value of the HOW parameter seems to leave the socket in a clean state
: that can execute a further connect without error.
: 
: I don't know what I'm doing wrong.  Has anybody done this who can tell
: me what the correct method is?

After the first connect, the socket has a port number, even though you didn't
assign one, and I imagine the system thinks that the port is still in use
until it can get all it's handshaking done with the other end.  If so, try
rebinding with a port of 0 and let the system pick a fresh outgoing port.
If that doesn't work, try setting the socket option SO_REUSEADDR.

Of course, it's possible I just screwed up somewhere.  I've never used
shutdown, actually.

Larry