SO_REUSEADDR SO_REUSEPORT

 

http://stackoverflow.com/questions/14388706/socket-options-so-reuseaddr-and-so-reuseport-how-do-they-differ-do-they-mean-t

SO_REUSEADDR       socketA        socketB       Result
---------------------------------------------------------------------
  ON/OFF       192.168.0.1:21   192.168.0.1:21    Error (EADDRINUSE)
  ON/OFF       192.168.0.1:21      10.0.0.1:21    OK
  ON/OFF          10.0.0.1:21   192.168.0.1:21    OK
   OFF             0.0.0.0:21   192.168.1.0:21    Error (EADDRINUSE)
   OFF         192.168.1.0:21       0.0.0.0:21    Error (EADDRINUSE)
   ON              0.0.0.0:21   192.168.1.0:21    OK
   ON          192.168.1.0:21       0.0.0.0:21    OK
  ON/OFF           0.0.0.0:21       0.0.0.0:21    Error (EADDRINUSE)

 测试代码:

#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#define BACKLOG 3

int main(int argc, char** argv) {
    if (argc < 3) {
        fprintf(stderr, "Usage: a.out <ip> <port>");
        return -1;
    }
    char* ip = argv[1];
    short port = atoi(argv[2]);

    struct sockaddr_in my_addr={0}, peer_addr={0};
    socklen_t peer_addr_size;
    int s, b, l, acc;
    my_addr.sin_family = AF_INET;
    my_addr.sin_port = htons(port);
    //my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    my_addr.sin_addr.s_addr = inet_addr(ip);

    s = socket(AF_INET, SOCK_STREAM, 0);
    int optval = 1;
    //setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
    setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &optval, sizeof(optval));

    b = bind(s, (struct sockaddr*)&my_addr, sizeof(struct sockaddr_in));
    if (b<0) {
        fprintf(stderr, "binding error: %s\n", strerror(errno));
        return -1;
    }
    printf("binded successfully\n");

    l = listen(s, BACKLOG);
    if (l <0) {
        fprintf(stderr, "listening error: %s\n", strerror(errno));
        return -1;
    }
    printf("listening...\n");

    peer_addr_size = sizeof(struct sockaddr_in);

    while(1) {
        acc = accept(s, (struct sockaddr*)&peer_addr, &peer_addr_size);
        if (acc <0) {
            fprintf(stderr, "accept error: %s\n", strerror(errno));
                    return -1;
            }
        printf("accepted\n");
        send(acc, "hello\n", 6, 0);
    }

    return 0;
}

 

https://unix.stackexchange.com/questions/605832/is-there-any-authoritative-place-that-says-multi-processes-or-threads-accepting

posted on 2017-01-08 22:58  明天有风吹  阅读(179)  评论(0编辑  收藏  举报

导航

+V atob('d2h5X251bGw=')

请备注:from博客园