-1

I need to use the following code in my c code and compile.

dd if=/dev/urandom bs=1 count=400 of=/dev/udp/SrcAddress.ai_addr/8000

This is giving the error

‘dd’ was not declared in this scope

How can I use this command inside my c code?

melpomene
  • 84,125
  • 8
  • 85
  • 148
Ashish Kurian
  • 51
  • 5
  • 12
  • 2
    `dd` is a shell command, not a c function :o –  May 19 '17 at 18:19
  • Umm... how well do you know C? Try the `system` function. – yellowantphil May 19 '17 at 18:19
  • 1
    `system()` is the way to execute any shell command from C. – Barmar May 19 '17 at 18:20
  • I suspect that `SrcAddress.ai_addr` is not a verbatim string but a place where you want to substitute a variable. But to tell you how to do that, we need to know what operating system you're using, because `/dev/udp` is nonstandard. – zwol May 19 '17 at 18:32

2 Answers2

2

You cannot use dd like that. Your C program is not a terminal and you cannot perform shell commands by just writing them in your code. One way to perform what you want is by using popen as following.

 #include <stdio.h>

 FILE *fd = popen("dd if=/dev/urandom bs=1 count=400 of=/dev/udp/SrcAddress.ai_addr/8000","w");
 pclose(fd);
RoiHatam
  • 876
  • 10
  • 19
0

It is possible that what you actually want to do is write the equivalent of this dd operation in C. That would look something like this.

int send_n_random_bytes_udp(unsigned int n, const struct sockaddr_in *dest)
{
    int rng = open("/dev/urandom", O_RDONLY);
    if (rng == -1) return -1;
    int sk  = socket(AF_INET, SOCK_DGRAM);
    if (sk  == -1) { close(rng); return -1; }

    int status = 0;
    for (unsigned int i = 0; i < n; i++) {
        char byte;
        if (read(rng, &byte, 1) != 1 ||
            sendto(sk, &byte, 1, 0,
                   (const struct sockaddr *)dest,
                   sizeof(struct sockaddr_in)) != 1) {
            status = -1;
            break;
        }
    }
    close(sk);
    close(rng);
    return status;
}
zwol
  • 135,547
  • 38
  • 252
  • 361
  • For that matter, they could use C to generate the random numbers instead of reading `/dev/urandom`. – yellowantphil May 19 '17 at 18:54
  • @yellowantphil I assume they want cryptographically sound random numbers. Reading `/dev/urandom` is much easier than dumping an implementation of ChaCha20 into the answer box. ;-) – zwol May 19 '17 at 19:01
  • In that case, they ought to be using `/dev/random`. – yellowantphil May 19 '17 at 19:05
  • @yellowantphil The current thinking is that `/dev/urandom` is cryptographically sound "enough" and `/dev/random` is unnecessary. IIRC FreeBSD has made them the same, even. – zwol May 19 '17 at 19:07
  • Huh, I didn't know that. Thanks. – yellowantphil May 19 '17 at 19:11
  • @yellowantphil See https://unix.stackexchange.com/questions/324209/when-to-use-dev-random-vs-dev-urandom and https://www.2uo.de/myths-about-urandom/ – zwol May 19 '17 at 20:11