How could I get my IP address (preferably in 192.168.0.1
format)?
Asked
Active
Viewed 4.8k times
9

Peter Mortensen
- 30,738
- 21
- 105
- 131

Jelly
- 4,522
- 6
- 26
- 42
-
1See previous [question](http://stackoverflow.com/questions/212528/get-the-ip-address-of-the-machine) – Louis Hugues Dec 27 '13 at 12:00
-
I'd like it in c code – Jelly Dec 27 '13 at 12:02
-
2look here: http://stackoverflow.com/questions/2283494/get-ip-address-of-an-interface-on-linux – Soosh Dec 27 '13 at 12:03
-
2`const char* my_address = "127.0.0.1";` works most of the time. – n. m. could be an AI Dec 27 '13 at 12:38
-
You may have several IP addresses.... – Basile Starynkevitch Dec 27 '13 at 13:32
2 Answers
15
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);

brm
- 3,706
- 1
- 14
- 14
-
1uClibc does not contain getifaddrs until very crecently. Do you know any other method which could be used on embedded devices? – Marki555 Dec 29 '14 at 00:44
7
For Linux:
To get all interfaces local to the machine use getifaddrs()
.
There is an example at the end of the page linked above.

alk
- 69,737
- 10
- 105
- 255