服务器/客户端c程序出错:“连接:非套接字上的套接字操作”

时间:2009-09-07 22:04:08

标签: c sockets

我正在研究套接字程序,编译时一切似乎都很好。首先,我编译并运行服务器,然后编译并运行客户端。服务器运行正常,但是当客户端启动时,我在Connect()函数中收到一条错误消息。虽然套接字似乎没问题,但客户端无法连接,服务器也看不到连接尝试。

错误消息是:

  

连接:非套接字上的套接字操作

这是服务器端代码:

if ((ListeningSocket = socket(AF_INET, SOCK_STREAM,0 )) == -1){
        printf("socket failed!\n");
        exit(1);
    }

     else
          printf("Server: socket() is OK!\n");


     ServerAddr.sin_family = AF_INET;
     ServerAddr.sin_port = htons(5000);
     ServerAddr.sin_addr.s_addr = INADDR_ANY; // any one for any network can connect
     memset(&(ServerAddr.sin_zero), '\0', 8); //


     if (bind (ListeningSocket, (struct sockaddr *)&ServerAddr, sizeof(struct sockaddr))==-1)
     {
          printf("Server: bind() failed!\n");
          exit (1);
     }
     else
          printf("Server: bind() is OK!\n");

     if (listen(ListeningSocket,5)== -1){
          printf("Server: Error listening on socket\n");
          exit (1);
     }
     else{
     printf("Server: listen() is OK, I'm waiting for connections...\n");
     printf("Server: accept() is ready...\n");}



         sin_size = sizeof(struct sockaddr_in);
     NewConnection = accept(ListeningSocket, (struct sockaddr *)&ClientAddr,(socklen_t *)&sin_size);
         printf("Server: accept() is OK...\n");
         printf("Server: Client connected, ready for receiving and sending data...\n");

.........
....

 //}

这是客户端代码:

if(SendingSocket = socket(AF_INET, SOCK_STREAM, 0) == -1)
     {
          printf("Client: socket() failed!");
          exit (1);
     }
     else
          printf("Client: socket() is OK!\n");


     ClientAddr.sin_family = AF_INET;
     ClientAddr.sin_port = htons(5000);  
     ClientAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
     memset(&(ClientAddr.sin_zero), '\0', 8); 




if  ( connect (SendingSocket, (struct sockaddr *)&ClientAddr,
                    sizeof(struct sockaddr)) == -1) 
        {
            perror("Connect");
            exit(1);
        }


     else
     {
          printf("Client: connect() is OK, got connected...\n");
          printf("Client: Ready for sending and/or receiving data...\n");
     }

....

1 个答案:

答案 0 :(得分:13)

您缺少一个括号。代码

if(SendingSocket = socket(AF_INET, SOCK_STREAM, 0) == -1)

应该阅读

if((SendingSocket = socket(AF_INET, SOCK_STREAM, 0)) == -1)

你写它的方式,就意味着

if(SendingSocket = (socket(AF_INET, SOCK_STREAM, 0) == -1))

表示:将socket()结果与-1比较,给出0或1,并将其分配给SendingSocket;然后测试它是真还是假。因此,假设socket()调用成功,则SendingSocket可能为0。