Unix域套接字客户端将无法连接

时间:2013-03-27 14:35:04

标签: c unix-socket

我一直在阅读“Linux编程接口”,试图了解套接字,尤其是unix域套接字。我已经阅读了第56章,它解释了一些一般概念,我正在尝试实现第57章中的客户端 - 服务器示例。

服务器代码似乎工作正常,但是当我尝试连接客户端时,对connect()的调用失败。

这是服务器代码:

#include<sys/un.h>
#include<sys/socket.h>
#include<stdio.h>
#define SV_SOCK_PATH "/tmp/boom"
#define BUF_SIZE 100
#define BACKLOG 5

int main(int argc, char *argv[]){
  struct sockaddr_un addr;
  int sfd, cfd;
  ssize_t numRead;
  char buf[BUF_SIZE];

  sfd = socket(AF_UNIX, SOCK_STREAM, 0);
  if(sfd!=0){
    printf("socket success\n");
  }
  else{
    printf("socket unsuccessful\n");
  }


  printf("socket declared\n");

  memset(&addr, 0, sizeof(struct sockaddr_un));
  addr.sun_family = AF_UNIX;
  strncpy(addr.sun_path, SV_SOCK_PATH, sizeof(addr.sun_path)-1);

  if (bind(sfd, (struct sockaddr *) &addr, sizeof(struct sockaddr_un))!=0){
    printf("bind unsuccessful\n");
  }
  else{
    printf("bind successful\n");
  }


  if (listen(sfd, BACKLOG) != 0){
  printf("listen failed\n");
  }
  else{
     printf("listen succeeded\n");
  }

  while(1){

    if( cfd = accept(sfd, NULL,NULL) != 0){
      printf("accept failed\n");
    }
    else{
      printf("accept succeeded\n");
    }

     while ((read(cfd, buf, BUF_SIZE)) > 0)
      write(1, buf, numRead); 
 }

}

客户端代码在这里:

#include<stdio.h>
#include<sys/un.h>
#include<sys/socket.h>
#define SV_SOCK_PATH "/tmp/boom"
#define BUF_SIZE 100
#define BACKLOG 5


int main(int argc, char *argv[]){
  struct sockaddr_un addr;
  int sfd, cfd;
  ssize_t numRead;
  char buf[BUF_SIZE];

  if(sfd = socket(AF_UNIX, SOCK_STREAM, 0) > 0){
    printf("socket successful\n");
  }
  else{
    printf("socket fucked\n");
  }

  memset(&addr, 0, sizeof(struct sockaddr_un));
  addr.sun_family = AF_UNIX;
  strncpy(addr.sun_path, SV_SOCK_PATH, sizeof(addr.sun_path)-1);

  if(connect(sfd, (struct sockaddr *) &addr, sizeof(struct sockaddr_un)) == -1){
    printf("connection unsuccessfully\n");
   }
  else{
     printf("connection successful\n");
  }

  if(numRead = read(0, buf, BUF_SIZE) > 0){
    printf("read successful\n");
    printf(buf);
  }
  else{
    printf("read unsuccessful\n");
  }

  if (write(sfd, buf, numRead) > 0){
    printf("write successful\n");
  }
  else{
    printf("write unsuccessful\n");
  }
}  

当我运行服务器时,我看到:

$ ./server 
socket success
socket declared
bind successful
listen succeeded

当我运行客户端时,我看到:

$ ./client 
socket successful
connection unsuccessfully
hello   # <-- I type this
read successful
hello
hwrite successful

如果有人能帮我解决这个问题,我将非常感激。

1 个答案:

答案 0 :(得分:3)

您在客户端

中缺少此代码的括号
if(sfd = socket(AF_UNIX, SOCK_STREAM, 0) > 0){

将其更改为

if((sfd = socket(AF_UNIX, SOCK_STREAM, 0)) > 0){

我还将服务器代码更改为如下所示:

.
.
.

socklen_t csize; 

while(1){

    cfd = accept(sfd, (struct sockaddr *)&addr,&csize);

    if (cfd < 0) {
      printf("accept failed: %s\n", strerror(errno));
    }
    else{
      printf("accept succeeded: %d\n", cfd);
    }

    .
    .
    .

现在它应该有效:)

始终注意操作员的优先权!