Originally Posted by
Salem
Look up strcmp() and strstr() to begin with.
Thanks Salem! Looks like strstr was what I needed! I had tried strcmp previously but was unable to get it to return the value I was looking for.
Here's what I came up with:
Code:
#include <stdio.h>
int main()
{
FILE *fp;
char path[1035]; // Set path array size to 1035.
fp = popen("ipconfig", "r"); // Open the command.
if(fp == NULL) { // If nothing is returned, error out.
printf("Failed to run command\n");
}
while(fgets(path, sizeof(path) - 1, fp) != NULL) { // Get output from command and print it.
//printf("%s", path);
// Search for our substrings
const char *lgString = path;
const char *smString = "IPv4";
char *ptr;
ptr = strstr(lgString, smString);
if(ptr) { // If found, filter out relevent strings by IP
const char *lgString2 = ptr;
const char *smString2 = "xxx.xxx.xxx";
char *ptr2;
ptr2 = strstr(lgString2, smString2);
if(ptr2) { // If found, print the resulting IP.
printf("Your IP address is: %s", ptr2);
}
}
}
pclose(fp);
return 0;
}
So this works to give me the value that I'm looking for. But is there possibly a better way to do this (overall, not just regarding the while loop)? (Better meaning more efficient, cleaner, or whatnot.)
As I mentioned, I'm new to C and always interested in seeing someone else's take on how to solve a particular problem. So if you're open to providing your feedback, I'd love to hear it!
Thanks again!
~ Tom