2

我一直在阅读“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

如果有人可以帮助我解决这个问题,我将不胜感激。

4

1 回答 1

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);
    }

    .
    .
    .

现在它应该可以工作了:)

始终注意运算符的优先级!

于 2013-03-27T15:27:46.183 回答