How to get IP address from sockaddr

前端 未结 6 1572
慢半拍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:22

    The following is taken from the example https://banu.com/blog/2/how-to-use-epoll-a-complete-example-in-c/epoll-example.c

                  struct sockaddr in_addr;
                  socklen_t in_len;
                  int infd;
                  char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
    
                  in_len = sizeof in_addr;
                  infd = accept (sfd, &in_addr, &in_len);
                  if (infd == -1)
                    {
                      if ((errno == EAGAIN) ||
                          (errno == EWOULDBLOCK))
                        {
                          /* We have processed all incoming
                             connections. */
                          break;
                        }
                      else
                        {
                          perror ("accept");
                          break;
                        }
                    }
    
                     s = getnameinfo (&in_addr, in_len,
                     hbuf, sizeof hbuf,
                     sbuf, sizeof sbuf,
                     NI_NUMERICHOST | NI_NUMERICSERV);
                     if (s == 0){
                         printf("Accepted connection on descriptor %d "
                             "(host=%s, port=%s)\n", infd, hbuf, sbuf);
                     }
    

提交回复
热议问题