Click here to Skip to main content
15,922,696 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have download a Winsock code example,and want to make the client and server communicate. When i build the server, it is successful, but the output is "bind () fail. press anykey to continue.......".
I paste the code here, to seek help from anyone who knows Winsock, many thanks.
C
#include <stdio.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
void main() {
  
    WSADATA wsaData;
    int iResult = WSAStartup( MAKEWORD(2,2), &wsaData );
    if ( iResult != NO_ERROR )
        printf("Error at WSAStartup()\n");
    
    SOCKET server;
    server = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
    if ( server == INVALID_SOCKET ) {
        printf( "Error at socket(): %ld\n", WSAGetLastError() );
        WSACleanup();
        return;
    }
   
    sockaddr_in service;
    service.sin_family = AF_INET;
    service.sin_addr.s_addr = inet_addr( "127.0.0.1" );
    service.sin_port = htons( 27015 );
    if ( bind( server, (SOCKADDR*) &service, sizeof(service) ) == SOCKET_ERROR ) {
        printf( "bind() failed.\n" );
        closesocket(server); 
        return;
    }
    
 
    if ( listen( server, 1 ) == SOCKET_ERROR )
        printf( "Error listening on socket.\n");
  
    SOCKET AcceptSocket;
    printf( "Waiting for a client to connect...\n" );
    while (1) {
        AcceptSocket = SOCKET_ERROR;
        while ( AcceptSocket == SOCKET_ERROR ) {
            AcceptSocket = accept( server, NULL, NULL );
        }
        printf( "Client Connected.\n");
        server = AcceptSocket; 
        break;
    }
    
 
    int bytesSent;
    int bytesRecv=SOCKET_ERROR;
    char sendbuf[32] = "Server: Sending Data.";
    char recvbuf[32] = "";
    
    bytesRecv = recv( server, recvbuf, 32, 0 );
    printf( "Bytes Recv: %ld\n", bytesRecv );
    
    bytesSent = send( server, sendbuf, strlen(sendbuf), 0 );
    printf( "Bytes Sent: %ld\n", bytesSent );
    return;
}
Posted
Updated 17-Oct-10 23:35pm
v2

1 solution

As stated in the documentation[^], you should call WSAGetLastError function on bind failure, in order to retrieve a more specific error code.
:)
 
Share this answer
 
Comments
Dalek Dave 18-Oct-10 5:42am    
Good Call.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900