Address family not supported by protocol

前端 未结 3 924
不思量自难忘°
不思量自难忘° 2021-02-08 01:24

Following code is a socket programming sample for a TCP client.

But when I run this, connect() is returned as Address family not supported by protocol.

I have he

相关标签:
3条回答
  • 2021-02-08 01:47

    Set the server address like this;

    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = inet_addr(host);
    addr.sin_port = htons(port);
    
    0 讨论(0)
  • 2021-02-08 01:58

    I seen this error during bind. Cause was of using localhost instead of IP:

    ./myprogram localhost:7777
    *** exception! `bind' failed for `localhost:7777' (97, Address family not supported by protocol)
    
    ./myprogram 127.0.0.1:7777
    OK! Listening...
    

    In addition: this error happens on one Linux host and does not appear on another. I check and compare network settings on this machines (lo device, /etc/hosts, /etc/host.conf, etc) and not found essential difference

    0 讨论(0)
  • 2021-02-08 02:08

    The code passes the wrong destination address and wrong number of arguments to inet_pton(). (For the latter the compiler should have warned you about, btw)

    This line

     inet_pton(AF_INET, "127.0.0.1", &server, sizeof(server));
    

    should be

     inet_pton(AF_INET, "127.0.0.1", &server.sin_addr);
    

    Verbatim from man inet_pton:

    int inet_pton(int af, const char *src, void *dst);

    AF_INET

    [...] The address is converted to a struct in_addr and copied to dst, which must be sizeof(struct in_addr) (4) bytes (32 bits) long.


    Not related to the problem, but also an issue, is that read() returns ssize_t not int.

    The following lines shall be adjusted:

    int n;
    [...]
    printf("%d, %s\n", n, buf);
    

    to become:

    ssize_t n;
    [...]
    printf("%zd, %s\n", n, buf);
    
    0 讨论(0)
提交回复
热议问题