title: bind: Socket operation on non-socket
body: <p>I writing a server and a client and keep getting 'bind: Socket operation on non-socket'.</p>
  
  <p>I've researched the heck out of this, have other code that runs in another application and have exhausted 8 hours trying to find this bug.</p>
  
  <p>The code is:</p>
  
  <pre><code>void TCPSocket::buildTCPSocket(int port)
  {
      initializeSocket1();
      getSocket();
      bindSocket();
      listenToSocket();
      acceptSocket();
           // now you can send() and recv() with the
          // connected client via socket connectedTCPSocket
  }
  
  void TCPSocket::getSocket()
  {
          // Get an internet domain socket AF_INET
      if(socket1 = socket(AF_INET, SOCK_STREAM,0) == -1)
      {
          perror("socket");
          exit(1);
      }    
  }
  
  
  void TCPSocket::bindSocket()
  {
    // Bind to a port on the host
      int myAddressSize = sizeof(myAddress);
      int bindReturnValue = bind(socket1, (struct sockaddr *) &amp;myAddress, AddressSize);
      if (bindReturnValue == -1)
      {
          perror("bind");  // &lt;== Error message generated here
          exit(1);
      }
      printf("Socket for TCP bound to port %d\n", port);    
  }
  </code></pre>
  
  <p>Also, prior to this, I memset the memory block with this function.</p>
  
  <pre><code>void TCPSocket::initializeSocket1()
  {
      // Fill tcpSocket struct with 0's
  
      memset(&amp;myAddress, '\0', sizeof(myAddress));
      myAddress.sin_family = AF_INET;
      myAddress.sin_addr.s_addr = INADDR_ANY;
     // Conver PORT to big-endian if necessary
      myAddress.sin_port = htons(this-&gt;port);
  }
  </code></pre>
  
  <p>Variables are declared in the header file of the class.</p>
  
  <pre><code>public:
      struct sockaddr_in myAddress, clientAddress;
  
      void buildTCPSocket(int newPort);
  
  private:
      int port;
      int socket1, socket2;
  
      socklen_t clientAddressLength;
  </code></pre>
  
  <p>-- Edit the code should be a little more clear now.  socket1 is initialized in getSocket().</p>
  
  <p>I've seen where a bunch of guys have missed the parens in the if but I think I eliminated that error by declaring myAddressSize and bindReturnValue.</p>
  
  <p>Any input is appreciated.<br>
  Thank you,
  Ted S</p>
  
  <p>Ok, problem solved.  Of course the problem is never where you are looking are you would have found it.  Here is the corrected code.  The problem was in a missing set of parens in the call to socket().</p>
  
  <pre><code>void TCPSocket::getSocket()
  {
          // Get an internet domain socket AF_INET
      if((socket1 = socket(AF_INET, SOCK_STREAM,0)) == -1)
      {
          perror("socket");
          exit(1);
      }    
  }
  </code></pre>
  
  <p>Thanks again!</p>