How to get Linux IP Address?

34 Views Asked by At

I am using a Colibri iMX7 with a Yocto Linux image running on it. After installing the Linux I can get the IP address with "ifconfig" in the terminal before installing my program, so I know what is my IP address. The problem I am having trouble with, is that I have a code written in C, and I want to get my IP from my code to display it on our screen. I could just set the IP that I know from the "ifconfig" command, but since I work with many boards, I need to have a code that will do it for all.

I am using the following function to get the IP address with no success:

void get_my_ip(char* ip){
    char command[] = "/sbin/ifconfig eth0 | grep 'inet addr' | cut -d: -f2 | awk '{print $1}'";
    
    FILE *file_ptr;

    file_ptr = popen(command,"r");
    char* ret;
    if(ip!=NULL){
        ret = fgets(ip, 19, file_ptr);
    }
    else{
        return;
    }
    if (pclose(file_ptr) != 0){
        fprintf(stderr," Error: Failed to close command stream (/proc/uptime) \n");
    }
}

The function should return to my ip variable the board ip (e.g. 192.168.1.123). I can see that the path "/sbin/ifconfig" is there if I connect trhough "sftp", but it will return nothing.

Coud someone help me with this issue or provide any info of how could I get the board IP address in C?

Thank you.

0

There are 0 best solutions below