How can I get client IPv4 address?

I am preparing a simple project and trying to get acquainted with the basics of socket programming in a Unix dev environment. At the moment, I have a basic setup of the server-side code to listen for incoming TCP connection requests from clients after creating the parent socket and setting the listening ...

int sockfd, newfd;    
unsigned int len;
socklen_t sin_size;
char msg[]="Test message sent";
char buf[MAXLEN];
int st, rv;
struct addrinfo hints, *serverinfo, *p; 
struct sockaddr_storage client;
char ip[INET6_ADDRSTRLEN];

.
. //parent socket creation and listen code omitted for simplicity
.

//wait for connection requests from clients
while(1)
  {
    //Returns the socketID and address of client connecting to socket
    if( ( newfd = accept(sockfd, (struct sockaddr *)&client, &len) ) == -1 ){
      perror("Accept");
      exit(-1);
    }

    if( (rv = recv(newfd, buf, MAXLEN-1, 0 )) == -1) {
      perror("Recv");
      exit(-1);
    }
    struct sockaddr_in *clientAddr = ( struct sockaddr_in *) get_in_addr((struct sockaddr *)&client);
    inet_ntop(client.ss_family, clientAddr, ip, sizeof ip);
    printf("Receive from %s: query type is %s\n", ip, buf);

    if( ( st = send(newfd, msg, strlen(msg), 0)) == -1 ) {
      perror("Send");
      exit(-1);
    }

    //ntohs is used to avoid big-endian and little endian compatibility issues
    printf("Send %d byte to port %d\n", ntohs(clientAddr->sin_port) );

    close(newfd);
  }

}

I found the function get_in_addronline and put it at the beginning of my code and used it to get the IP address of the client connected ...

// get sockaddr, IPv4 or IPv6:
void *get_in_addr(struct sockaddr *sa)
{
  if (sa->sa_family == AF_INET) {
    return &(((struct sockaddr_in*)sa)->sin_addr);
  }

  return &(((struct sockaddr_in6*)sa)->sin6_addr);
}

but the function always returns the IPv6 IP address, since this property is sa_familyset to.

My question is that the IPv4 IP address is stored somewhere in the data that I use, and if so, how can I access it?

Many thanks for your help!

+3
3

IPv6-, , . IPv6 IPv4 1-1, IP- .

, -, .

+4

. "getipv4addr" "getipv6addr" -. , IPv4 IPv6- , .

0

IPv6-, IPv4, IPv4- .

IPv4 , 12, 13, 14 15 s6_addr.

0

Source: https://habr.com/ru/post/1738042/


All Articles