0%

tcp 选项 SO_REUSEADDR

SO_REUSEADDR 用于调整解决地址复用问题

bind() 前设置 SO_REUSEADDR,用于将 TIME_WAIT 重复绑定使用

int yes = 1;

if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
    perror("server: socket");
    continue;
}

if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) {
    perror("setsockopt");
    exit(1);
}

if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
    close(sockfd);
    perror("server: bind");
    continue;
}

Ref

  1. SO_REUSEADDR 套接字选项作用
  2. 从SO_REUSEADDR选项说起