Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Server Sockets - bind() error

Everything compiles without errors and warnings. I start the program. I visit localhost:8080 and the program stops - great. I try to run the program again and I get Error: unable to bind message. Why?

Code:

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include <errno.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define PORT 8080
#define PROTOCOL 0
#define BACKLOG 10

int main()
{
  int fd;
  int connfd;

  struct sockaddr_in addr; // For bind()
  struct sockaddr_in cliaddr; // For accept()
  socklen_t cliaddrlen = sizeof(cliaddr);

  // Open a socket
  fd = socket(AF_INET, SOCK_STREAM, PROTOCOL);
  if (fd == -1) {
    printf("Error: unable to open a socket\n");
    exit(1);
  }

  // Create an address
  //memset(&addr, 0, sizeof addr);
  addr.sin_addr.s_addr = INADDR_ANY;
  addr.sin_family = AF_INET;
  addr.sin_port = htons(PORT);

  if ((bind(fd, (struct sockaddr *)&addr, sizeof(addr))) == -1) {
    printf("Error: unable to bind\n");
    printf("Error code: %d\n", errno);
    exit(1);
  }

  // List for connections
  if ((listen(fd, BACKLOG)) == -1) {
    printf("Error: unable to listen for connections\n");
    printf("Error code: %d\n", errno);
    exit(1);
  }

  // Accept connections
  connfd = accept(fd, (struct sockaddr *) &cliaddr, &cliaddrlen);
  if (connfd == -1) {
    printf("Error: unable to accept connections\n");
    printf("Error code: %d\n", errno);
    exit(1);
  }

  //read(connfd, buffer, bufferlen);
  //write(connfd, data, datalen);
  //  close(connfd);

  return 0;
}
like image 817
chuckfinley Avatar asked Nov 30 '25 20:11

chuckfinley


1 Answers

Use the SO_REUSEADDR socket option before calling bind(), in case you have old connections in TIME_WAIT or CLOSE_WAIT state.

Uses of SO_REUSEADDR?

like image 191
Barmar Avatar answered Dec 03 '25 11:12

Barmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!