Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get my IP address in C on Linux? [duplicate]

How could I get my IP address (preferably in 192.168.0.1 format)?

like image 270
Jelly Avatar asked Dec 27 '13 11:12

Jelly


People also ask

What's My IP from Linux command line?

Find IP address with ip addr command in Linux All we need is to open the terminal then type ip addr in the prompt. The number next to inet is our IP address. This command will list IP address, MAC address, MTU size and other information about a network interface. We can also type ip addr or ip a for short.


2 Answers

This example code lists both the interface name (e.g. lo or eth0) together with the currently assigned IP address, for all the IPv4 network interfaces that exist on your computer:

getifaddrs(&addrs);
tmp = addrs;

while (tmp) 
{
    if (tmp->ifa_addr && tmp->ifa_addr->sa_family == AF_INET)
    {
        struct sockaddr_in *pAddr = (struct sockaddr_in *)tmp->ifa_addr;
        printf("%s: %s\n", tmp->ifa_name, inet_ntoa(pAddr->sin_addr));
    }

    tmp = tmp->ifa_next;
}

freeifaddrs(addrs);
like image 163
brm Avatar answered Oct 13 '22 06:10

brm


For Linux:

To get all interfaces local to the machine use getifaddrs().

There is an example at the end of the page linked above.

like image 22
alk Avatar answered Oct 13 '22 05:10

alk