真心求教!!UNIX域编程中bind() 和listen()函数出错!!
刚接触UNIX域编程
运行时 bind() 和listen()一直报错代码如下:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/select.h>
#include <sys/un.h>
int main()
{
struct sockaddr_un address;
int sock=0, conn;
int addrLength;
char buf[1024] = {0};
char *msg = "I has recived";
if ((sock = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
{
perror("socket");
exit(0);
}
unlink("/mnt/hgfs/share/unix/foo.sock");
address.sun_family = AF_UNIX;
strcpy(address.sun_path, "/mnt/hgfs/share/unix/foo.sock");
addrLength = sizeof(address.sun_family)+strlen(address.sun_path);
printf("sock: %d\n",sock);
if(bind(sock, (struct sockaddr *) &address, addrLength))
perror("bind");
if(listen(sock, 3))
perror("listen");
while((conn = accept(sock, (struct sockaddr *) &address, &addrLength)) >= 0)
{
printf("int while!\n");
recv(conn, buf, sizeof(buf), 0);
printf("%s/n", buf);
send(conn, msg, strlen(msg), 0);
}
return 0;
}
运行时一直报告以下两个错误:
bind: Operation not permitted
listen: Invalid argument
请了解的人帮忙解决!!!
------解决方案--------------------addrLength = sizeof(address.sun_family)+strlen(address.sun_path);
似乎应该是:
addrLength = sizeof(struct sockaddr_un);
另外看一下/mnt/hgfs/share/unix/foo.sock的权限问题。
------解决方案--------------------确定/mnt/hgfs/share/unix/foo.sock文件已经不存在,确定/mnt/hgfs/share/unix目录你有写权限。