简体   繁体   中英

C Socket programming on windows errors on listen but no errno

I've done socket programming in other languages but never dealt with doing it in C directly. I'm trying to set up a simple server to listen on port 8080 under Windows. I'm using the gcc that comes with mingw to compile the code.



    #include <stdio.h>
    #include <string.h>
    #include <WinSock2.h>
    #include <stdint.h>
    #include <time.h>

        int main(void) {

        int s;      
        int len;
        char  buffer[1025];  
        struct sockaddr_in servAddr; 
        struct sockaddr_in clntAddr; 

        int clntAddrLen; //length of client socket addre

    //Build local (server) socket add

        memset(&servAddr, 0, sizeof(servAddr));
        servAddr.sin_family = AF_INET;
        servAddr.sin_port = htons(8080);
        servAddr.sin_addr.s_addr = htonl(INADDR_ANY);

       //create socket
        if((s=socket(AF_INET, SOCK_STREAM, 0) %lt; 0 )){
            perror("Error: Socket Failed!");
                printf("%d\n", errno);
            exit(1);
        }

    //bind socket to local address and port
        if((bind(s,(struct sockaddr*)&servAddr, sizeof(servAddr)) %lt; 0))
        {
            perror("Error:bind failed!");
                printf("%d\n", errno);
            exit(1);
        }

        for(;;)
        {
            len = recvfrom(s,buffer, sizeof(buffer),0,(struct sockaddr*)&clntAddr, &clntAddrLen);

            //send string
            sendto(s, buffer, len, 0, (struct sockaddr*)&clntAddr, sizeof(clntAddr));
        }

    }

When I run the code it errors out binding but there's no error. This code was taken and slightly modified from this thread: Windows Socket Programming in C

But there's no error code. The output prints that there's no error. It fails at the bind and I'm not sure why. I've been piecing together a few different sources. I literally just want something that can do a hello world/3 way handshake in C on Windows.

Thanks in advance.

This is incorrect due to operator precedence :

if((s=socket(AF_INET, SOCK_STREAM, 0) < 0 )){

as < has higher precedence than = . This means that the code will assign 1 or 0 to s depending on result of socket(AF_INET, SOCK_STREAM, 0) < 0 . Change to:

if((s=socket(AF_INET, SOCK_STREAM, 0)) < 0 ){

Use WSAGetLastError() to obtain failure reason, not errno . From the MSDN bind() reference page:

If no error occurs, bind returns zero. Otherwise, it returns SOCKET_ERROR, and a specific error code can be retrieved by calling WSAGetLastError.

On Windows WSAStartup() must be invoked before any socket functions are called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM