Home > OS >  Cannot bind socket to network in C
Cannot bind socket to network in C

Time:07-05

I am trying to create a simple HTTP server in C.

Unfortunately, I'm not quite sure why this is the case, but I am getting "Cannot assign requested address" whenever I try to bind the socket to the address.

if ( bind(servfd, (struct sockaddr*)&servaddr, servaddr_size) != 0 )
    {
        fprintf(stderr, "Failed to bind the socket to the network.\n");
        fflush(stdout);
        perror("bind failed. Error");
        return 1;
    }

Here is my server address:

    struct sockaddr_in servaddr;

    memset(&servaddr, '0', sizeof(servaddr));

    servaddr.sin_family = AF_INET;
    servaddr.sin_port = INADDR_ANY;
    servaddr.sin_addr.s_addr = htons(PORT);

And here is my server opt:

if ( setsockopt(servfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) != 0 )
    {
        fprintf(stderr, "Failed to set sock opt.\n");
        fflush(stdout);
        return 1;
    }

I've tried to htonl the INADDR_ANY, I've tried to use inet("127.0.0.1"), inet("0.0.0.0"), and I've tried to change the port from multiple times. Hell, I tried running the app with sudo in case it was a permission error; it wasn't.

Any ideas?

CodePudding user response:

I think you may have the assignment of these two lines reversed:

servaddr.sin_port = INADDR_ANY;
servaddr.sin_addr.s_addr = htons(PORT);

Try:

servaddr.sin_port = htons(PORT);
servaddr.sin_addr.s_addr = INADDR_ANY;
  • Related