1

I heard that there are types of ip addresses like primary address etc. and tried to get the ip address using the below command

ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1'

and got the result as below

192.168.122.1
192.168.168.1
172.16.142.1
192.168.1.102

so from the above can someone answer which my primary address is?

jww
  • 97,681
  • 90
  • 411
  • 885
Ravi
  • 27
  • 1
  • 2
  • 1
    Possible duplicate of [How to I get the primary IP address of the local machine on Linux and OS X?](https://stackoverflow.com/questions/13322485/how-to-i-get-the-primary-ip-address-of-the-local-machine-on-linux-and-os-x) You should also state the programming language you are working with. You will get better results. – jww Jun 14 '17 at 12:39

3 Answers3

2

When a machine has different IP addresses, it is impossible to define the primary IP from a network only point of view. But a machine normaly has a name that can be obtained by the command uname -n, or by the POSIX function uname. Once you have that name, you can find the IP address corresponding to it by the getent command or the gethostbyname function: what is called the primary IP address is the first address returned.

So here you could use:

getent hosts $(uname -n) | head -1 | cut -f 1 -w
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
1

There is no such things as "primary address" or "primary device". You have multiple ip addresses related to multiple networt devices.

You could find out what devices allows you to access to the internet and finds its local ip.

To do that, issue the command route. It will output something like

Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
default         192.168.0.254   0.0.0.0         UG    0      0        0 eth0
192.168.1.0     0.0.0.0         255.255.255.0   U     0      0        0 eth0

Now all you need is to use the device on the line default and use it in this command:

ifconfig <DEVICENAME> | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*'
blue112
  • 52,634
  • 3
  • 45
  • 54
0

Primary address depends on your usage, there is nothing as such at the network level. If you use one IP to access your server usually, you may call it primary and the network devices won't know the difference.

Jagatveer Singh
  • 185
  • 2
  • 12