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];
.
.
.
while(1)
{
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);
}
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!