How can I get my own IP address and save it to a variable in a shell script?
|
It's not so easy if you want to take into account wlan and other alternative interfaces. If you know which interface you want the address for (e.g., eth0, the first Ethernet card), you can use this:
In other words, get me the network configuration information, look for |
|||||
|
|
I believe the "modern tools" way to get your ipv4 address is to parse 'ip' rather than 'ifconfig', so it'd be something like:
or something like that. |
|||||||||||||||
|
|
I use this one-liner:
Uses |
|||
|
|
|
Why not simply do |
|||||||||
|
|
Depends what you mean by own IP address. Systems have IP addresses on several subnets (sometimes several per subnet), some of which IPv4, some IPv6 using devices like ethernet adapters, loopback interfaces, VPN tunnels, bridges, virtual interfaces... I you mean the IP address by which another given device may reach your computer, you have to find out which subnet that is, and which version of IP we're talking about. Also, bear in mind that because of NAT performed by firewall/routers, the IP address of an interface may not be the same as a remote host sees an incoming connection from your computer coming from. When there is fancy source routing or per protocol/port routing it can be difficult to find out which interface would be used to talk to one remote computer over a given protocol and even then, there's no guarantee that the IP address of that interface may be directly addressable by the remote computer wanting to establish a new connection to your computer. For IPv4 (probably works for IPv6 as well), a trick that works in many unices including Linux to find out the IP address of the interface used to reach a given host is to use a connect(2) on a UDP socket and use getsockname(): For instance, on my home computer:
Would be used to find out the IP address of the interface via which I would reach 8.8.8.8 (google's DNS server). It would return something like "192.168.1.123" which is the address of the interface for the default route to the internet. However, google wouldn't see a DNS request from my machine as coming from that IP address which is a private one, as there's NAT performed by my home broadband router. connect() on a UDP socket doesn't send any packet (UDP is connection-less), but prepares the socket by querying the routing table. |
|||
|
|

