I am writing a small test application that will determine what one's IP address is on a given subnet. I'm passing the address of a pointer from main() to getCompIPAddr(). I know that the pointer is being edited as expected once it gets to that function.
The problem is that, in some instances, the while loop returns more than a single string containing an IP address (searches for "IPv4") and passes that to the if() block. The if() block correctly adjusts the value of the pointer but if there's more than one value, the pointer is set to whatever the last value is (usually NULL).
What I'm not able to figure out is how to break out of the while loop when the correct value is found. I've tried variations of the code below (specifically, the if(ptr) block), but with the same result--the application hangs and never finishes running.
Code:
#include <stdio.h>
#include <stdlib.h>
void getCompIPAddr(char** a);
int main()
{
char ipAddr[16] = "000.000.000.000";
char * pIpAddr = ipAddr;
printf("pIpAddr before passing to getCompIPAddr(): %s\n", pIpAddr);
getCompIPAddr(&ipAddr);
printf("Your new main() IP address is: %s\n", *pIpAddr);
return 0;
}
void getCompIPAddr(char** a)
{
FILE *fp;
char path[1035];
fp = popen("ipconfig", "r");
if(fp == NULL) {
printf("Failed to run command\n");
}
while(fgets(path, sizeof(path) - 1, fp) != NULL) { // Get output from command.
//printf("%s", path);
// Search substring(s)
const char * lgString = path;
const char * smString = "IPv4";
char * ptr = strstr(lgString, smString);
if(ptr) { // If found, filter out relevent strings by IP
//printf("ptr: %s", ptr);
const char * lgString2 = ptr;
const char * smString2 = "192.168.0";
char * ptr2 = strstr(lgString2, smString2);
printf("ptr2: %s", ptr2);
if(ptr2)
{
*a = ptr2;
//printf("*a: %s\n", *a);
break;
}
}
}
}
What is it that I'm missing that's not allowing this to work?