Quote:> Hi, guys.
> I have a piece of code read like following,
> int fd;
> int host=0;
> fd=socket(PF_INET, ... );
> while (host < HOST_NUM) {
> if (connect(fd, (struct sockaddr*)&host_addr[host],
> sizeof(struct sockaddr))==0) {//OK
> break;
> }
> host++;
> }
> if (host >= HOST_NUM) {
> err_exit("All servers are out of service");
> exit(1);
> }
> My design is to use 'fd' to try to connect one of multiple hosts, in
> host_addr[] array. If all connect() failed, an error is displayed and
> program exits. However, when I test this code, I found that if
> host_addr[0] is out of service (connect returns -1), then all other
> host_addr[] will also make connect() return -1 even if they are actually
> providing services. Then I tried to move the socket() line into while
> loop, it unexpectedly WORKS.
connect() modifies the socket structure before it tries to connect
to the remote address, so the socket is "used up" even if your
connection fails. This is how it was designed, so it "expectedly"
works.
Quote:> So my question is that, if I insist on putting socket() out of while
> loop to save the time consumption of calling socket() again and again,
> what should I do to make connect() WORK as I wished?
If your objective is to save time by not executing system calls,
don't bother --the time it takes to get a reply from the remote
host is what determines the execution speed (and it far exceeds
time spent in system calls). Worrying about system calls such as
socket() and close() in a network application falls under the
heading "useless micro-optimisations".
Oh yes, don't forget that you have to close() the socket as well,
or you'll run out of file descriptors:
...
while (host < HOST_NUM) {
fd=socket(PF_INET, ... );
if (connect(fd, (struct sockaddr*)&host_addr[host],
sizeof(struct sockaddr)) == 0) {//OK
break;
}
close(fd);
host++;
Quote:}
...
Take care,
--
Stefaan
--
--PGP key available from PGP key servers (http://www.pgp.net/pgpnet/)--
Ninety-Ninety Rule of Project Schedules:
The first ninety percent of the task takes ninety percent of
the time, and the last ten percent takes the other ninety percent.