Hi I created a function that takes in an accepted sockFD as input and outputs the ip address in presentation form to a string. The function seems to be working fine until I get down to packing the string with a call from inet_ntop which returns a null pointer and thus giving me my error. The error reads as No space left on device which I don’t understand since I have plenty of ram and rom. Anyways bellow is the function that I am using.
void getTheirIp(int s, char *ipstr){ // int s is the incoming socketFD, ipstr points the the calling
// functions pointer.
socklen_t len;
struct sockaddr_storage addr;
len = sizeof(addr); //I want to store my address in addr which is sockaddr_storage type
int stat;
stat = getpeername(s, (struct sockaddr*)&addr, &len); // This stores addrinfo in addr
printf("getTheirIP:the value of getpeername %d\n",stat);
// deal with both IPv4 and IPv6:
if ((stat=addr.ss_family) == AF_INET) { // I get the size of the sock first
printf("getTheirIP:the value of addr.ss_family is %d\n",stat);
ipstr = malloc(INET_ADDRSTRLEN); // I allocate memory to store the string
struct sockaddr_in *s = (struct sockaddr_in *)&addr; // I then create the struct sockaddr_in which
// is large enough to hold my address
if(NULL == inet_ntop(AF_INET, &s->sin_addr, ipstr, sizeof(ipstr))){ // I then use inet_ntop to
printf("getTheirIP:the value of inet_ntop is null\n");// retrieve the ip address and store
perror("The problem was"); // at location ipstr
}
} else { // AF_INET6 this is the same as the above except it deals with IPv6 length
ipstr = malloc(INET6_ADDRSTRLEN);
struct sockaddr_in6 *s = (struct sockaddr_in6 *)&addr;
inet_ntop(AF_INET6, &s->sin6_addr, ipstr, sizeof(ipstr));
}
printf("%s",ipstr);
}
I left out the rest of the program because it is too big to fit and I only want to focus on fixing this part. However bellow I will show you part of my main() that calls this function.
newSock = accept(listenSock,(struct sockaddr *)&their_addr,&addr_size);
char *someString;
getTheirIp(newSock,someString);
Any help would be great. Thanks!
That
sizeofis wrong sinceipstris a pointer (it will yield the size of the pointer, something like4or8). You need to pass the available length of theipstrbuffer.