0

While executing below code in a console:

int ret = system("iptables -t filter -L"); 

ret will get value 1 and there will be a list of rules displayed in the console. The problem is that I also want to get the list of rules inside my program. I am doing this with the below solution:

int ret = system("iptables -t filter -L >> filter-table.txt"); /* read filter-table.txt file to get the list */ 

Is there anyway else to get the list?

3
  • 7
    ...by using a popen()-family function rather than system()? Commented Dec 9, 2014 at 1:17
  • 1
    ...seriously, though: If you want output, system() is the wrong call. (If you want detailed control over argv parsing, or immunity from shellshock-style vulnerabilities, system() is also the wrong call. I'd argue that it's only very rarely the right call, personally). Commented Dec 9, 2014 at 1:19
  • 2
    system() is primarily useful for writing shell scripts in languages other than the shell and proof-of-concept security exploits. Commented Dec 9, 2014 at 1:20

2 Answers 2

5

As mentioned by @Charles Duffy, and @Kevin, system() is not the function you want. popen() is more suitable. The following should work. Please note, if you are using gcc and compile with -std=c99 flag, you need to add #define _POSIX_C_SOURCE 2 before #include <stdio.h>

#include <stdio.h> #include <error.h> #define PATH_MAX 1024 int main(void) { FILE *fp; int status; char path[PATH_MAX]; fp = popen("iptables -t filter -L", "r"); if (fp == NULL) { perror("popen"); return -1; } while (fgets(path, PATH_MAX, fp) != NULL) { printf("%s", path); /* do something you want with the return data */ } status = pclose(fp); if (status == -1) { perror("pclose"); } return 0; } 
Sign up to request clarification or add additional context in comments.

Comments

2

You should install iptables-devel on your distro and directly include de library in your code to build something cleaner. In place of using the output.

You'll find an hint on this link : http://www.bani.com.br/2012/05/programmatically-managing-iptables-rules-in-c-iptc/

1 Comment

Libiptc does not exist anymore. Check the last question and answer at netfilter.org/documentation/FAQ/netfilter-faq.html#toc4.5

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.