1

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?

1 Answer 1

1

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; 
Sign up to request clarification or add additional context in comments.

1 Comment

oh my god......

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.