Re: interesting behavior.. this right ?

Richard B. Johnson (root@analogic.com)
Sat, 12 Apr 1997 21:14:04 -0400 (EDT)


On Sat, 12 Apr 1997, Ian Main wrote:

>
>
> Hi, I'm no expert at this, and I don't know what the correct behavior is,
> but this seems a little odd.
>
> If you call a bind before connect(), and you bind to an address that has
> no route to the host your trying to reach, the connect() will hang. I set
> up an alarm to try to get around this, but it only seems to work once,
> after that, the signal won't break it out of the connect call. (I even
> had to kill -9 it once..)
>
> Here's an example of what I'm talking about. It always hangs on the
> connect call.. shouldn't it return an error ?
>
> Like I say, I don't know the proper behavior but I just thought I'd check.
> :) If anyone knows how to work around this, I'd be very greatful.
>
>
> Ian
>
>
> ---------------------------------------------------------------
>
> #include <stdio.h>
> #include <sys/socket.h>
> #include <sys/types.h>
> #include <netinet/in.h>
> #include <arpa/inet.h>

#include <signal.h>

void dummy(int unused)
{
}

>
>
> int main(void)
> {
> struct sockaddr_in addr;
> struct sockaddr_in local_addr;
> int sock;
>
> sock = socket(AF_INET, SOCK_STREAM, 0);
>
> /* bind to localhost */
> local_addr.sin_family = AF_INET;
> local_addr.sin_port = htons(0);
> inet_aton("127.0.0.1", &local_addr.sin_addr);
>
> if (bind(sock, (struct sockaddr *) &local_addr, sizeof(struct sockaddr_in)) < 0)
> perror("bind");
>
> /* connect to remote host (sunsite's IP) */
> addr.sin_family = AF_INET;
> addr.sin_port = htons(23);
> inet_aton("152.2.254.81", &addr.sin_addr);
>
> printf("connecting...\n");

signal(SIGALRM, dummy);
alarm(5);
>
> if (connect(sock, (struct sockaddr *) &addr, sizeof(struct sockaddr_in)) < 0)
> perror("connect");

alarm(0);
>
> printf("done.");
> return(0);
> }

These modifications will get you out of any system call. If the connection
failed, the errno will be "interrupted system call", when tha alarm clock
goes off. Remember to cancel the alarm, alarm(0) upon success or your
next system call may fail...

Cheers,
Dick Johnson
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Richard B. Johnson
Project Engineer
Analogic Corporation
Voice : (508) 977-3000 ext. 3754
Fax : (508) 532-6097
Modem : (508) 977-6870
Ftp : ftp@boneserver.analogic.com
Email : rjohnson@analogic.com, johnson@analogic.com
Penguin : Linux version 2.1.33 on an i586 machine (66.15 BogoMips).
Warning : I read unsolicited mail for $350.00 per hour. Supply billing address.
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-