Link to home
Start Free TrialLog in
Avatar of squirm
squirm

asked on

Winsock - Can't Bind() to Socket

I'm trying to send() info from one server socket and then Listen() - Accept() -  Recv() the info on another server socket (same machine). Both sockets need to be bound to  PORT 80 but have different addresses. I connect() and send OK, no errors. Then I create a new socket() and try to bind() to it and the bind() fails with a WSAENOTSOCK error.
Here's the code:

// Creates a socket for listening
if ((SockListen = socket (AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
{
   WSACleanup();
}        

// Set the Server connection information  
ClientIn.sin_family      = AF_INET;
ClientIn.sin_port        = htons (80);
ClientIn.sin_addr.s_addr = htonl (INADDR_ANY);
   
// Binds the address and port information to the socket    
if ((bind_ID = bind (SockListen, (LPSOCKADDR) &ClientIn, sizeof(ClientIn))) == SOCKET_ERROR)
{
   closesocket (SockSend);
   closesocket (SockRecv);
   WSACleanup();
}
 
if ((list_ID = listen (SockListen, MAX_LISTEN_Q)) == SOCKET_ERROR)
{
   closesocket (SockSend);
   closesocket (SockRecv);
   WSACleanup();
}

P.S. I couldn'y get bind() to work for the connect()- send() either so I skipped it.    

 
ASKER CERTIFIED SOLUTION
Avatar of faster
faster

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of faster
faster

If your machine is multi-homing, then you should try specify the IP address you want in each bind(), rather than using INADDR_ANY.
Avatar of squirm

ASKER

So I listen() on port 80 but connect() on any port.  How do I send() information to a web server and then wait for the answer? Don't I have to send() through port 80 for the web server to receive the information?  Also, I didn't bind() before I connnected() but I did connect to 80 and I can send() without an error.  Should I bind()first, is there a benefit?  
So you need to connect to another web server.  The fact that the web server is listening on port 80 does not mean that you have to talk with it on port 80, you can on any port.  Normally, you should bind first, and most of the time when bind(), you specify the port to 0, this means that you don't care which port it is and the system will then select a port for you.

Of course, for your own web server, you have to bind it to 80, that is because it is a server, and without having a fixed port, the clients will not know where to find your server.