socket() returns -1

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • shailesh333
    New Member
    • Aug 2009
    • 10

    socket() returns -1

    I have written a small piece of code in 'c' for a simple server
    However when I call the socket function , it returns the value -1.
    What could be the problem??

    Any help will be appreciated... Thanks in advance.

    I am using dev c++ as my IDE, and running the code in windows platform
    The code is as follows:

    Code:
    #include<stdio.h>
    //#include <ws2tcpip.h>
    #include <winsock2.h>
    
    
    
    int main()
    {
        char cin;
        struct sockaddr_in server ;
        struct sockaddr_in dest ;
        int mysocket ;
        int socksize = sizeof(struct sockaddr_in);
        char msg[] = "server speaking:\tHello World !\n";
     memset(&server, 0 ,sizeof(server));
        server.sin_family = AF_INET ;
        server.sin_port = 8082 ;
        server.sin_addr.s_addr = INADDR_ANY ;//inet_addr("127.0.0.1") ; //INADDR_ANY ;
        
        mysocket = socket(AF_INET, SOCK_STREAM, 0);
        printf("socket function return value:\t%d\n",mysocket);
        int bindreturn = bind(mysocket, (struct sockaddr*)&server, sizeof(struct sockaddr));
        printf("%d\n",bindreturn);
       
        
        listen(mysocket,1);
        
        int consocket = accept(mysocket, (struct sockaddr *)&dest, &socksize);
        if (consocket < 0)
        printf("waiting for client to connect:\t%d\n",consocket);
        while (consocket < 0)
        {
        }
        printf("waiting for client to connect:\t%d\n",consocket);
              
     
        while(consocket)
        {
                printf("%d\n",consocket);
            int consocket = accept(mysocket, (struct sockaddr *)&dest, &socksize);
            printf("Incoming connection from %s - sending welcome\n", inet_ntoa(dest.sin_addr));
            send(consocket, msg, strlen(msg), 0);
     
            
        }
        close(consocket);
        close(mysocket);
        
        scanf("%c", &cin);
        return 0;
    }
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    You haven't called WSAStartup. WinSock2 is not Berekley sockets, although it is designed to be fairly compatible, read up on WinSock2.

    Comment

    Working...