How to get IP address from sockaddr

前端 未结 6 1579
慢半拍i
慢半拍i 2020-12-28 14:25

I want to try and get the ip address of a client after calling accept. This is what I have so far, but I just end up getting some long number that is clearly not an ip addr

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-28 15:23

    You can use getnameinfo function that is available for Linux and Windows. From Linux man pages https://linux.die.net/man/3/getnameinfo:

    getnameinfo - address-to-name translation in protocol-independent manner

    Example for C/C++ (Linux):

    #include 
    #include 
    #include 
    
    char host[NI_MAXHOST]; // to store resulting string for ip
    if (getnameinfo((sockaddr*)&client, c_len,
                      host, NI_MAXHOST, // to try to get domain name don't put NI_NUMERICHOST flag
                      NULL, 0,          // use char serv[NI_MAXSERV] if you need port number
                      NI_NUMERICHOST    // | NI_NUMERICSERV
                   ) != 0) {
       //handle errors
    } else {
        printf("Connected to: %s\n", host);     
    }
    

    This is clean up of @enthusiasticgeek answer. His answer has a working example with accept call.

提交回复
热议问题