Click to See Complete Forum and Search --> : Problem with bind


highlord101
August 19th, 2008, 06:25 AM
Here's my function

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <unistd.h>
#include <fcntl.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <errno.h>
#include <signal.h>

#define SERVER_PATH "/tmp/srv"
#define BUFFER_LENGTH 250

static int open_sock(void) {

int sd=-1;
int r=-1;
struct sockaddr_un serv_addr;

if(sd = socket(AF_UNIX, SOCK_STREAM, 0) < 0) {

perror("socket() failed");
return sd;
}

memset(&serv_addr,0,sizeof(serv_addr));
serv_addr.sun_family = AF_UNIX;
strcpy(serv_addr.sun_path, SERVER_PATH);

if(bind(sd, (struct sockaddr*)&serv_addr, sizeof(&serv_addr)) < 0) {
perror("bind() failed");
return -1;
}

chmod (serv_addr.sun_path,0777);

listen(sd, 20);
return sd;
}

Basically, I am trying to open a Unix Socket for listening request. However, when I execute the file, the bind() always return an error with
"bind() failed: Socket operation on non-socket"

Can anyone tell me what might cause this issue in bind? Thanks
The socket 'sd' value before bind is 0, which I find kind of strange.
Also, the path '/tmp/srv' is non-existence before socket creation. Should I make this path first?

Edders
August 19th, 2008, 10:50 AM
What happens if you use AF_INET to opend the socket rather than AF_UNIX?

highlord101
August 19th, 2008, 09:24 PM
Unfortunately, the AF_INET fails as well. I am thinking could it be the fact that there is something in the Linux setting itself that disallow the creation of socket. I'll keep searching. Thanks

Richard.J
August 20th, 2008, 03:54 AM
I think you have a problem with the socket creation and the error checking:
[code]
if( (sd = socket(AF_UNIX, SOCK_STREAM, 0) ) < 0) {
[code]

What you are doing is checking if socket() < 0 and then assigning the value of this comparison to sd. The additional parenthesis in the above code should do the trick.

HTH,
Richard

highlord101
August 26th, 2008, 09:28 PM
Yes, it does. Thanks bro..
How careless of me.