2017-04-18 108 views
0

運行時,程序給出在非插座上的插座操作:在設置插座選項和裝訂插座時出錯

在非插座上的插座操作:綁定插座時發生錯誤。

後,當我用setsockopt() 再次給了我錯誤:

socket operation on non socket, error while setting options to socket. 
我目前使用Ubuntu 16.04

。 操作系統或我的代碼有問題嗎? (因爲我已經看到我在這裏使用 端口沒有被任何其他程序,我試圖改變 端口號10000和56000也是範圍)

#include<stdio.h> 
#include<stdlib.h> 
#include<string.h> 
#include<sys/types.h>    
#include<sys/socket.h>  
#include<netinet/in.h>  
#include<arpa/inet.h>  
#include<errno.h>   

#define PORT 7890 

int main() 
{ 
    int sock_fd, new_sockfd; 
    struct sockaddr_in host_addr, client_addr;    
    socklen_t sin_size; 
    int recv_length, yes = 1; 
    char buffer[1024];          


    if(sock_fd = socket(AF_INET, SOCK_STREAM, 0) == -1)  
    { 
     perror("in creating socket \n"); 
     exit(-1); 
    } 
    else 
     printf("Socket: SUCCESS \n"); 

    if(setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, &yes,sizeof(int)) == -1) 
     perror("while setting socket option SO_REUSEADDR \n"); 
    else 
     printf("Socket Option: SUCCESS \n"); 



    host_addr.sin_family = AF_INET;    
    host_addr.sin_port = htons(PORT);   
    host_addr.sin_addr.s_addr = 0;    
    memset(&(host_addr.sin_zero), '\0', 8);  




    if(bind(sock_fd, (struct sockaddr *)&host_addr, sizeof(struct sockaddr)) == -1) 
     perror("while binding \n"); 
    else 
     printf("Binding: SUCCESS \n"); 


    if(listen(sock_fd, 5) == -1) 
     perror("while listening \n"); 
    else 
     printf("Listen: SUCCESS \n"); 


    while(1) 
    { 

     sin_size = sizeof(struct sockaddr_in); 

     new_sockfd = accept(sock_fd, (struct sockaddr *)&client_addr, &sin_size); 

      if(new_sockfd == -1) 
      { 
       perror("failed to accept \n"); 
       exit(-1); 
      } 
      else 
       printf("accept: SUCCESS \n"); 
      printf("Server got connction from IP ADDRESS: %s, PORT NUMBER:%d \n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port)); 
    send(new_sockfd, "HELLO BASTARDS !\n", 16, 0); 

     recv_length = recv(new_sockfd, &buffer, 1024, 0); 

      while(recv_length > 0) 
      { 
       printf("Recieved %d Bytes \n", recv_length); 



       recv_length = recv(new_sockfd, &buffer, 1024, 0);      
      } 

     close(new_sockfd); 
    } 




return 0; 
} 
+4

這個'如果(sock_fd =插座(AF_INET,SOCK_STREAM,0)== -1)'不會做你期望的。注意運營商的優先順序。 '=='綁定比'='更緊密。 – alk

回答

0

常用運算符優先級問題:

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

應該

if((sock_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)  
+1

爲什麼這個錯誤在網絡代碼中一遍又一遍地重複了呢?他們爲什麼着迷於出現錯誤的複合布爾表達式?開發人員是否懶得使用兩條可以輕鬆調試的代碼?擋住我:( – ThingyWotsit