Subject: bind: Address already in use
To: None <netbsd-help@netbsd.org>
From: Ravi Josyula <rjosyula@riverstonenet.com>
List: netbsd-help
Date: 04/02/2002 17:35:00
Hi,

I just wrote a test program which works fine on Solaris but not on BSD.
When I run my program the first time, everything is okay. It's only the
second time that it complains saying the address is already in use. If
I remove the file, it will work, but then again, it will work once.
I tried setting the socket options to SO_REUSERADDR, but that did not
help.

Any suggestions are welcome!

Thanks,
Ravi.

===================
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>

#define SOCK_PATH "/tmp/sock"

void main()
{
    int fd, len;
    struct sockaddr_un local;
    int reuse = 1;

    fd = socket(AF_UNIX, SOCK_STREAM, 0);
    if (fd == -1) {
        perror("listen");
        exit(1);
    }
    local.sun_family = AF_UNIX;
    strcpy(local.sun_path, SOCK_PATH);
    unlink(local.sun_path);
    len = strlen(local.sun_path) + sizeof(local.sun_family);

    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&reuse,
sizeof(reuse));
    setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, (char *)&reuse,
sizeof(reuse));

    if (bind(fd, (struct sockaddr *)&local, len) == -1) {
        perror("bind");
        exit(1);
    }
    close(fd);
}

=================