Thread: Strange C socket error

  1. #1
    Registered User
    Join Date
    Mar 2009
    Posts
    1

    Question Strange C socket error

    Hi, I'm writing a socket based server program in C right now and I got a
    "Socket operation on non-socket" error from a bind command in code which seems to be perfectly legal.
    Also, the changes I made do the exact same thing as before but without error checking and the bind command succeeds. Thanks to anyone who can tell me why the error occurred.

    CODE GENERATING ERROR

    Code:
    //Create and name the server's socket
        if( server_sockfd=socket(AF_INET,SOCK_STREAM,0) == -1){
            perror("Socket creation failed");
            exit(EXIT_FAILURE);
        }
    
        server_address.sin_family=AF_INET;                      //accept connections from any IP address
        server_address.sin_addr.s_addr = htonl(INADDR_ANY);     //using the SERVER_PORT
        server_address.sin_port = htons(SERVER_PORT);
    
        if(bind(server_sockfd, (struct sockaddr *)&server_address,addr_len)==-1){
            perror("Socket binding failed");
            exit(EXIT_FAILURE);
        }


    FIXED CODE

    Code:
    //Create and name the server's socket
        server_sockfd=socket(AF_INET,SOCK_STREAM,0) ;
    
        server_address.sin_family=AF_INET;                      //accept connections from any IP address
        server_address.sin_addr.s_addr = htonl(INADDR_ANY);     //using the SERVER_PORT
        server_address.sin_port = htons(SERVER_PORT);
    
        if(bind(server_sockfd, (struct sockaddr *)&server_address,addr_len)==-1){
            perror("Socket binding failed");
            exit(EXIT_FAILURE);
        }

  2. #2
    Registered User
    Join Date
    Apr 2008
    Posts
    396
    Code:
      server_sockfd=socket(AF_INET,SOCK_STREAM,0) == -1
    the operator precedence is not the one you're thinking about, the line above will set server_sockfd to 0 or 1 depending on socket()==-1 result. Use parentheses.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. An error is driving me nuts!
    By ulillillia in forum C Programming
    Replies: 5
    Last Post: 04-04-2009, 09:15 PM
  2. Making C DLL using MSVC++ 2005
    By chico1st in forum C Programming
    Replies: 26
    Last Post: 05-28-2008, 01:17 PM
  3. failure to import external C libraries in C++ project
    By nocturna_gr in forum C++ Programming
    Replies: 3
    Last Post: 12-02-2007, 03:49 PM
  4. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  5. ras.h errors
    By Trent_Easton in forum Windows Programming
    Replies: 8
    Last Post: 07-15-2005, 10:52 PM