简体   繁体   中英

Can't execlp netcat

I'm trying to exec the following command from C:

netcat 127.0.0.1 4444

This is my code:

#include <unistd.h>

int main() {
    execlp("/usr/bin/netcat", "127.0.0.1", "4444", 0);
}

However, I keep getting the error: Error: no ports specified for connection .

To answer a few questions I feel may come up:

  • which netcat gives /usr/bin/netcat
  • I've tried using execvp and got the same results
  • Running the command normally, ie via a terminal, is successful (Usually i also give the -e /bin/bash argument but I've omitted it for simplicity. Adding it doesn't change the results.)

The problem is, that your first argument is "4444". Why?

Look at this line:

execlp("/usr/bin/netcat", "127.0.0.1", "4444", 0);

The first argument to execlp() is the binary to execute. The rest of the arguments will form the argv[] -vector passed to the process.

By convention, argv[0] should contain the name of the executable and the first "real" argument is argv[1] , which is "4444" in your case. So what you do is the equivalent on the shell of

netcat 4444

and the correct call would be:

execlp("/usr/bin/netcat", "netcat", "127.0.0.1", "4444", 0);

Btw. the use of execlp() makes only sense when calling a binary without a full path, since it looks for the correct path itself (using the PATH environment variable). Otherwise, execl() should be used. But it will work anyway.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM