I need to use IP address of the eth0 interface of a PC (Linux OS - IPv4). How can I define it as a constant variable without knowing the IP address in advance?
Asked
Active
Viewed 1,747 times
0
-
What OS? You'll need to make a system call to look it up if you don't know it *a priori*. – Flexo May 13 '12 at 13:08
-
Language itself has nothing to do with it. You either need a library that would be more or less portable, or simply a system-call. – ScarletAmaranth May 13 '12 at 13:10
-
This question is very ambiguous. You have not provided sufficient info. What it will be used for? You can store it as `unsigned char[4]` (or 6 in case of IPv6), as a string, in the format XXX.XXX.XXX.XXX, as one of the BSD sockets' host struct types (struct inaddr etc.)... !? – May 13 '12 at 13:10
-
http://stackoverflow.com/questions/2021549/get-ip-address-in-c-language -> Similar. – ScarletAmaranth May 13 '12 at 13:11
-
I think what's more important question is, why do you need it to be const ? – Roee Gavirel May 13 '12 at 13:22
2 Answers
2
You cannot.
There are two ways to define a constant quantity in C: the preprocessor (#define
) and constants (const something
). Both of these require that the value of the constant be known at compile time¹. So if your aim was to have a way to refer to this IP without having the possibility of overwriting it with another value during program execution, it's simply not doable.

Jon
- 428,835
- 81
- 738
- 806
2
If you have them as pointer to an address buffer you can. Export a pointer to const
qualified type
extern your_address_type const*const addr;
You'd have to have your library code see something like
static your_address_type my_address;
your_address_type const*const addr = &my_address;
Inside your library you can then initialize my_address
properly, client code only would see addr
and wouldn't be able to change it.

Jens Gustedt
- 76,821
- 6
- 102
- 177