Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

c - How to find out if the eth0 mode is static or dhcp?

I want to use a C program to get if the ip of the network interface is set manually or via dhcp.

I've tried to use the following code and it has worked in Debian, but it hasn't worked in OpenWrt. I want to know how to write a C program doing this in OpenWrt. I have tried to use this:

#include <stdio.h>
int main(void)
{
    FILE *fp;
    char buffer[80];
    fp=popen("cat /etc/network/interfaces |grep ^iface\ br-lan | awk -F ' ' '{print $4}'","r");
    fgets(buffer, sizeof(buffer), fp);
    printf("%s", buffer);
    pclose(fp);
}

This code is working in Debian, but it isn't working normally in OpenWrt, so I want to know how to write a program to get the same result.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

for OpenWRT you can get a such information with the following command:

$uci get network.lan.proto

so I take the program you put in your question and I change only the command used to get information:

#include <stdio.h> <br>
int main(void)
{
    FILE *fp;
    char buffer[80];
    fp=popen("uci get network.lan.proto","r");
    fgets(buffer, sizeof(buffer), fp);
    printf("%s", buffer);
    pclose(fp);
}

to see all network interfaces available in your OpenWRT you can use the following command:

$uci show network

You can avoid using calling linux command in your c by using the libuci. The libuci contains C function to execute uci commands without passing via popen ( popen is used to execute external command from shell).

The libuci exist by default in the development environment of OpenWRT, not need to download it, no need to build it and no need to install it on your OpenWRT machine

You can use libuci in this way

#include <uci.h>
void main()
{
    char path[]="network.lan.proto";
    char buffer[80];
    struct  uci_ptr ptr;
    struct  uci_context *c = uci_alloc_context();

    if(!c) return;

    if ((uci_lookup_ptr(c, &ptr, path, true) != UCI_OK) ||
        (ptr.o==NULL || ptr.o->v.string==NULL)) { 
        uci_free_context(c);
        return;
    }

    if(ptr.flags & UCI_LOOKUP_COMPLETE)
            strcpy(buffer, ptr.o->v.string);

    uci_free_context(c);

    printf("%s
", buffer);
}

(Not tested)

and when you compile your program you have to add the -luci in the compilation command gcc


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...