How to get my own IP address and save it to a variable in a shell script? Announcing the...

How to compute a Jacobian using polar coordinates?

Preserving file and folder permissions with rsync

Married in secret, can marital status in passport be changed at a later date?

Processing ADC conversion result: DMA vs Processor Registers

Marquee sign letters

Why aren't road bicycle wheels tiny?

What is the purpose of the side handle on a hand ("eggbeater") drill?

What's called a person who works as someone who puts products on shelves in stores?

What to do with someone that cheated their way though university and a PhD program?

What is ls Largest Number Formed by only moving two sticks in 508?

What is the definining line between a helicopter and a drone a person can ride in?

Could a cockatrice have parasitic embryos?

Arriving in Atlanta (after US Preclearance in Dublin). Will I go through TSA security in Atlanta to transfer to a connecting flight?

Was there ever a LEGO store in Miami International Airport?

When I export an AI 300x60 art board it saves with bigger dimensions

What happened to Viserion in Season 7?

Why would the Overseers waste their stock of slaves on the Game?

Writing a T-SQL stored procedure to receive 4 numbers and insert them into a table

Suing a Police Officer Instead of the Police Department

In search of the origins of term censor, I hit a dead end stuck with the greek term, to censor, λογοκρίνω

Is there a way to fake a method response using Mock or Stubs?

How would it unbalance gameplay to rule that Weapon Master allows for picking a fighting style?

Did war bonds have better investment alternatives during WWII?

How would you suggest I follow up with coworkers about our deadline that's today?



How to get my own IP address and save it to a variable in a shell script?



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30 pm US/Eastern)
2019 Community Moderator Election Results
Why I closed the “Why is Kali so hard” questionHow to get IP Address using shell script?Is there an easy way to programmatically extract IP address?Assigning IP address to environment variableHow can I list net work devices and ipv4 address on linux without ifconfig/ip commandPutting external IP into a variable - grep operation failedGetting the IP address of a given interfaceHow to get the network status (online/offline) and attribute it to a variable in shell script?How can I get my external IP address in a shell script?How to “send” variable to sub-shell?Assigning IP address to environment variableEnvironment variable for ip addressHow to get IP Address using shell script?How to get and print a user's public IP address in a Shell Script?Get the latest value of an environment variable is a bash shell scriptHow to get SSH client IP Address using shell script?Posix shell script - Save multi line command output to variable





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ margin-bottom:0;
}







61















How can I get my own IP address and save it to a variable in a shell script?










share|improve this question




















  • 2





    A word of caution: There are a lot of "works on my system" answers here that may not be portable to other environments. You have to decide if you want something that works for you or something that can be shared. Every system has multiple IPs. A portable solution answers the Q: "what IP do I use to reach blah?" A works on my system solution answers the Q: "what's my IP?" with the A: "I think you mean this one…" This should be portable unix.stackexchange.com/a/402160/9745

    – Bruno Bronosky
    Apr 1 '18 at 17:42




















61















How can I get my own IP address and save it to a variable in a shell script?










share|improve this question




















  • 2





    A word of caution: There are a lot of "works on my system" answers here that may not be portable to other environments. You have to decide if you want something that works for you or something that can be shared. Every system has multiple IPs. A portable solution answers the Q: "what IP do I use to reach blah?" A works on my system solution answers the Q: "what's my IP?" with the A: "I think you mean this one…" This should be portable unix.stackexchange.com/a/402160/9745

    – Bruno Bronosky
    Apr 1 '18 at 17:42
















61












61








61


23






How can I get my own IP address and save it to a variable in a shell script?










share|improve this question
















How can I get my own IP address and save it to a variable in a shell script?







networking shell-script ip






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Feb 12 '12 at 16:21









Mat

40.1k8124128




40.1k8124128










asked Mar 3 '11 at 13:17









Tom BritoTom Brito

1,07981733




1,07981733








  • 2





    A word of caution: There are a lot of "works on my system" answers here that may not be portable to other environments. You have to decide if you want something that works for you or something that can be shared. Every system has multiple IPs. A portable solution answers the Q: "what IP do I use to reach blah?" A works on my system solution answers the Q: "what's my IP?" with the A: "I think you mean this one…" This should be portable unix.stackexchange.com/a/402160/9745

    – Bruno Bronosky
    Apr 1 '18 at 17:42
















  • 2





    A word of caution: There are a lot of "works on my system" answers here that may not be portable to other environments. You have to decide if you want something that works for you or something that can be shared. Every system has multiple IPs. A portable solution answers the Q: "what IP do I use to reach blah?" A works on my system solution answers the Q: "what's my IP?" with the A: "I think you mean this one…" This should be portable unix.stackexchange.com/a/402160/9745

    – Bruno Bronosky
    Apr 1 '18 at 17:42










2




2





A word of caution: There are a lot of "works on my system" answers here that may not be portable to other environments. You have to decide if you want something that works for you or something that can be shared. Every system has multiple IPs. A portable solution answers the Q: "what IP do I use to reach blah?" A works on my system solution answers the Q: "what's my IP?" with the A: "I think you mean this one…" This should be portable unix.stackexchange.com/a/402160/9745

– Bruno Bronosky
Apr 1 '18 at 17:42







A word of caution: There are a lot of "works on my system" answers here that may not be portable to other environments. You have to decide if you want something that works for you or something that can be shared. Every system has multiple IPs. A portable solution answers the Q: "what IP do I use to reach blah?" A works on my system solution answers the Q: "what's my IP?" with the A: "I think you mean this one…" This should be portable unix.stackexchange.com/a/402160/9745

– Bruno Bronosky
Apr 1 '18 at 17:42












21 Answers
21






active

oldest

votes


















30














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:



ip="$(ifconfig | grep -A 1 'eth0' | tail -1 | cut -d ':' -f 2 | cut -d ' ' -f 1)"


In other words, get me the network configuration information, look for eth0, get that line and the next one (-A 1), get only the last line, get the second part of that line when splitting with :, then get the first part of that when splitting with space.






share|improve this answer



















  • 1





    I added an additional grep to your code to ignore any interface with "eth0:" in it; this now works as I expect (giving only the "eth0" IP address and not any sub-interfaces (eth0:0, eth0:1, etc.): ip="$(ifconfig | grep -v 'eth0:' | grep -A 1 'eth0' | tail -1 | cut -d ':' -f 2 | cut -d ' ' -f 1)"

    – user32250
    Feb 12 '13 at 19:49








  • 5





    You can skip the first grep by using ifconfig eth0

    – Bryan Larsen
    Dec 1 '14 at 16:29






  • 3





    ifconfig is deprecated, you should use ip address instead

    – alexises
    Dec 23 '15 at 15:42



















63














I believe the "modern tools" way to get your ipv4 address is to parse 'ip' rather than 'ifconfig', so it'd be something like:



ip4=$(/sbin/ip -o -4 addr list eth0 | awk '{print $4}' | cut -d/ -f1)
ip6=$(/sbin/ip -o -6 addr list eth0 | awk '{print $4}' | cut -d/ -f1)


or something like that.






share|improve this answer





















  • 4





    ip is available on all the Red Hat and Fedora distros I've used. ip is part of the iproute2 package (linuxfoundation.org/collaborate/workgroups/networking/iproute2). ifconfig and route are supposedly deprecated, although they continue to be used by a lot of people, particularly in scripts. ip is much more parsable, in my opionion.

    – jsbillings
    Mar 3 '11 at 15:13








  • 3





    ip is also available on all Debian and Debian based distros I've seen. It's part of the iproute package which is marked as important.

    – Arrowmaster
    Mar 3 '11 at 23:43






  • 2





    This is absolutely how it should be done, I would downvote the other answers for their use of ifconfig. ip is part of the iproute2 package which is many a distro by default. It's in most good repos to. en.wikipedia.org/wiki/Iproute2

    – jwbensley
    Sep 15 '12 at 12:13








  • 3





    @jsbillings Why /sbin/ip instead of ip?

    – l0b0
    Jan 15 '13 at 13:02






  • 1





    This is an excellent answer! The combination of awk and cut is mildly amusing to me, here's a possible alternative which may not actually be better: ip -o -4 addr show eth0 | awk '{ split($4, ip_addr, "/"); print ip_addr[1] }'

    – Swiss
    Jun 15 '17 at 21:21



















30














Why not simply do IP=$(hostname -I) ?






share|improve this answer





















  • 3





    hostname -i gives me just 127.0.0.1, hostname -I gives me the correct IP-Adress...

    – student
    Sep 15 '12 at 12:41













  • @student yes indeed, I have tested it on a machine that has can resolve its hostname, as the manpage says -i Display the network address(es) of the host name. Note that this works only if the host name can be resolved. Avoid using this option; use hostname --all-ip-addresses

    – Andrei
    Sep 15 '12 at 12:49













  • How can I configure my machine to resolve its hostname?

    – student
    Sep 15 '12 at 12:58











  • the easiest way is adding it to /etc/hosts, along with the corresponding IP address

    – Andrei
    Sep 16 '12 at 10:06








  • 3





    No -I on FreeBSD, but you can use dig +short `hostname -f`

    – Tigger
    Jun 3 '15 at 0:07



















23














If you want the address of an interface, the easiest way is to install moreutils then:



anthony@Zia:~$ ifdata -pa br0
172.16.1.244


ifdata answers pretty much every question you'd be tempted to parse ifconfig output for.



If you want to find out your IP address as the outside sees it (beyond any NAT, etc.), there are plenty of services that'll do it. One is fairly easy:



anthony@Zia:~$ curl ifconfig.me
173.167.51.137





share|improve this answer
























  • Oh goodness, thank you for this answer. Never heard of moreutils before. I was seriously considering writing my own little C program to do exactly that.

    – Chris Harrington
    Feb 28 '16 at 2:02











  • It would be nice to have ifdata added into iproute2. Maybe a new binary called ipdata

    – Swiss
    Jun 15 '17 at 21:25













  • ifdata is good BUT it doesn't supports ipv6.

    – BringBackCommodore64
    Jul 6 '17 at 11:29





















11














To get IPv4 and IPv6 addresses, and not assume the main interface is eth0 (these days em1 is more common), try:



ips=$(ip -o addr show up primary scope global |
while read -r num dev fam addr rest; do echo ${addr%/*}; done)




  • -o uses the one-line output format, which is easier to process with read, grep, etc.


  • up excludes devices that aren't active


  • scope global excludes private/local addresses such as 127.0.0.1 and fe80::/64


  • primary excludes temporary addresses (assuming you want an address that doesn't change)






share|improve this answer



















  • 1





    This has to be the best answer because 1) it doesn't assumes a device name, 2) it uses 'ip' as opposed to old school 'ifconfig', and 3) it supports ipv6 as well.

    – BringBackCommodore64
    Jul 6 '17 at 11:31













  • I agreed, it the best start for most use cases. You can pass -4/-6 to filter address types. You can also easily get other interface parameters. Personally, I dislike while loop and I prefer grep -o 'inet6? [0-9a-f.:]*' | cut -f 2 -d ' '

    – Jezz
    May 18 '18 at 7:42



















7














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:



perl -MSocket -le 'socket(S, PF_INET, SOCK_DGRAM, getprotobyname("udp"));
connect(S, sockaddr_in(1, inet_aton("8.8.8.8")));
print inet_ntoa((sockaddr_in(getsockname(S)))[1]);'


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.






share|improve this answer































    7














    ipa=$(ip route get 8.8.8.8| grep src| sed 's/.*src (.*)$/1/g')

    ipa=$(hostname -i|cut -f2 -d ' ')





    share|improve this answer
























    • Using -I instead of -i is better as you would want to ignore loopback adresses, so the final command would be ipa=$(hostname -I|cut -f1 -d ' ')

      – Karl.S
      Oct 17 '17 at 22:00






    • 1





      If grep isn't enough, don't pipe it to something else. Just use the something else (sed, awk, etc.).

      – Bruno Bronosky
      Aug 11 '18 at 16:58



















    7














    I don't mean to be a jerk, but there really is a right way and this is it. You trim the output of ip route to get only the source IP. Depending on what IP you are trying to reach, "my own ip address" (OP's words) will be different. If you care about reaching the public internet, using Google's 8.8.8.8 DNS server is pretty standard. So...



    The short answer is:



    ip route get 8.8.8.8 | sed -n '/src/{s/.*src *//p;q}'


    Here's the detailed explanation



    If I want the ip I use to reach the internet, I use this:



    pi@et3:~ $ ip route get 8.8.8.8 | sed -n '/src/{s/.*src *//p;q}'
    10.55.0.200


    If I want the ip I use to reach something on my VPN, I use this:



    pi@et3:~ $ ip route get 172.31.0.100 | sed -n '/src/{s/.*src *//p;q}'
    172.29.0.9



    This next one is really just for illustrative purposes. But, it should work on any Linux system. So, you can use this to demonstrate that, yes, all machines have multiple IP addresses at all times.




    If I wanted the ip I use to reach myself, I would use this:



    pi@et3:~ $ my_ip=$(getent hosts $(cat /etc/hostname) | awk '{print $1; exit}')
    pi@et3:~ $ ip route get $my_ip | sed -n '/src/{s/.*src *//p;q}'
    127.0.0.1


    More about that sed command



    First let me say that when choosing unix tools, you try to choose the tools that require the fewest pipes. So, while some answers will pipe ifconfig to grep to sed to head, that is rarely ever necessary. When you see it, it should raise a red flag that you are taking advice from someone with little experience. That doesn't make the "solution" wrong. But, it probably could use some streamlining.



    I have chosen sed because it is more terse than the same workflow in awk. I don't think any other tool but those 2 would be appropriate.



    Let's examine what sed -n '/src/{s/.*src *//p;q}' does:



    sed            # the sed executable located via $PATH
    -n # no output unless explicitly requested
    ' # begin the command space
    /src/ # regex match the string 'src'
    { # begin a block of commands **
    s/.*src *// # regex match "anything followed by 'src' followed by any number of spaces" and replace it with "nothing"
    p # print (explicitly, remember) the result
    ; # designate the end of the command
    q # quit
    } # end the block of commands
    ' # end the command space

    ** all of which will be performed "on match"
    - otherwise only the first command to following the match would be performed "on match"
    - any other commands would be performed whether there was a match or not


    More about my network



    My ifconfig shows that I have tun0 for my VPN and eth0 for my lan.



    pi@et3:~ $ ifconfig
    eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
    inet 10.55.0.200 netmask 255.255.252.0 broadcast 10.55.3.255
    inet6 fe80::71e6:5d7c:5b4b:fb25 prefixlen 64 scopeid 0x20<link>
    ether b8:27:eb:b2:96:84 txqueuelen 1000 (Ethernet)

    lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
    inet 127.0.0.1 netmask 255.0.0.0
    inet6 ::1 prefixlen 128 scopeid 0x10<host>
    loop txqueuelen 1 (Local Loopback)

    tun0: flags=4305<UP,POINTOPOINT,RUNNING,NOARP,MULTICAST> mtu 1500
    inet 172.29.0.9 netmask 255.255.255.255 destination 172.29.0.10
    inet6 fe80::3a8e:8195:b86c:c68c prefixlen 64 scopeid 0x20<link>
    unspec 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00 txqueuelen 100 (UNSPEC)

    wlan0: flags=4099<UP,BROADCAST,MULTICAST> mtu 1500
    ether b8:27:eb:e7:c3:d1 txqueuelen 1000 (Ethernet)





    share|improve this answer
























    • ip route get 8.8.8.8 | sed -n '/src/{s/.*src *//p;q}' gave me 10.1.2.3 uid 1002. So I add to append | awk '{print $1}' to keep only the IP address.

      – wisbucky
      4 hours ago



















    2














    On FreeBSD you can use



    dig +short `hostname -f`


    This may work for other environments, depends on your set-up.






    share|improve this answer
























    • I believe this is dependant on the configuration of /etc/resolv.conf and how the network router handles local hostnames. It's fine to use this in your environment if you test it and it works. But if you do so, you are building a "brittle" system that is going to cause others problems if you share this. Use with caution.

      – Bruno Bronosky
      Apr 1 '18 at 17:28



















    2














    Assuming that you may have various interfaces of various name but that you want the first non-localhost one and non-ipv6, you may try:



    ip=`ip addr show |grep "inet " |grep -v 127.0.0. |head -1|cut -d" " -f6|cut -d/ -f1`





    share|improve this answer
























    • ip=$(ifconfig | grep -oP '(?<=inet addr:)S*' | grep -v 127)

      – rcjohnson
      Nov 17 '15 at 17:12



















    1














    I use this one-liner:



    IP=$(/sbin/ifconfig | grep -e "inet:" -e "addr:" | grep -v "inet6" | grep -v "127.0.0.1" | head -n 1 | awk '{print $2}' | cut -c6-)


    Uses ifconfig (widely available), does not take localhost address, does not bind you to a given interface name, does not take into account IPv6 and tries to get the IP of the first network interface available.






    share|improve this answer































      0














      I needed to do this within an alias to start a radio server on my wired NIC. I used



      ip addr | egrep -i "inet.+eth1" | awk -F[ /] '{print $6}' | tr -d [:space:]





      share|improve this answer
























      • egrep is depreciated. Use grep -E instead.

        – Yokai
        Jan 25 '18 at 9:23



















      0














      Some commands are working on centos 6 or 7, the below command working on both,



      #!/bin/sh

      serverip=`/sbin/ifconfig eth0 | grep "inet" | awk '{print $2}' | awk 'NR==1' | cut -d':' -f2`

      echo $serverip





      share|improve this answer
























      • that's way too much grep | awk | awk . line can be shortened to /sbin/ifconfig eth0 | awk '$1 == "inet" { print substr($2,6); next ; } '

        – Archemar
        Aug 6 '15 at 11:23











      • I accepted, can you check both centos6 and 7?. centos 7.x /sbin/ifconfig eth0 | awk '$1 == "inet" { print substr($2,6); next ; }' 35.104.41 centos6.x (Working fine) /sbin/ifconfig eth0 | awk '$1 == "inet" { print substr($2,6); next ; }' 192.168.0.1

        – lakshmikandan
        Aug 7 '15 at 4:32





















      0














      Assuming you need your primary public IP as it seen from the rest of the world, try any of those:



      wget http://ipecho.net/plain -O - -q
      curl http://icanhazip.com
      curl http://ifconfig.me/ip





      share|improve this answer































        0














        This snippet avoids hard-coding the device name (like 'eth0') and will use ip instead of ifconfig:



        /sbin/ip addr | grep 'state UP' -A2 | tail -n1 | awk '{print $2}' | cut -f1  -d'/'


        It will return the IP of the first active device listed in the output of ip addr. Depending on your machine, this can be an ipv4 or ipv6 address.



        To store it into a variable, use:



        ip=$(/sbin/ip addr | grep 'state UP' -A2 | tail -n1 | awk '{print $2}' | cut -f1  -d'/')





        share|improve this answer































          0














          myip=$(curl -kLs "http://api.ipify.org")


          or



          myip=$(wget -q "http://api.ipify.org" -O -)





          share|improve this answer































            0














            all the solutions using awk/sed/grep seem overly complex and ugly for my situation... so i came up with this really simple solution BUT beware cus it makes some assumptions, namely the assumption that the LAST interface is the one you're interested. if you're ok with that then this is pretty clean:



            ifconfig | awk '/net / { x = $2 } END { print x }'



            otherwise you could do some silly if statement to test for a specific prefix or whatever criteria you may have.






            share|improve this answer































              0














              Simple Command to fine IP Address with default interface.



              ip route | grep src | awk '{print $NF; exit}'


              Tested on All Unix OS






              share|improve this answer































                0














                You should use ip (instead of ifconfig) as it's current, maintained, and perhaps most importantly for scripting purposes, it produces a consistent & parsable output. Following are a few similar approaches:



                If you want the IPv4 address for your Ethernet interface eth0:



                $ ip -4 -o addr show eth0 | awk '{print $4}'
                192.168.1.166/24


                As a script:



                $ INTFC=eth0  
                $ MYIPV4=$(ip -4 -o addr show $INTFC | awk '{print $4}')
                $ echo $MYIPV4
                192.168.1.166/24



                The output produced above is in CIDR notation. If CIDR notation isn't wanted, it can be stripped:



                $ ip -4 -o addr show eth0 | awk '{print $4}' | cut -d "/" -f 1 
                192.168.1.166


                Another option that IMHO is "most elegant" gets the IPv4 address for whatever interface is used to connect to the specified remote host (8.8.8.8 in this case). Courtesy of @gatoatigrado in this answer:



                $ ip route get 8.8.8.8 | awk '{ print $NF; exit }'
                192.168.1.166


                As a script:



                $ RHOST=8.8.8.8  
                $ MYIP=$(ip route get $RHOST | awk '{ print $NF; exit }')
                $ echo $MYIP
                192.168.1.166


                This works perfectly well on a host with a single interface, but more advantageously will also work on hosts with multiple interfaces and/or route specifications.



                ip would be my preferred approach, but it's certainly not the only way to skin this cat. Here's another approach that uses hostname if you prefer something easier/more concise:



                $ hostname --all-ip-addresses | awk '{print $1}'  


                Or, if you want the IPv6 address:



                $ hostname --all-ip-addresses | awk '{print $2}'  





                share|improve this answer































                  0














                  This may not be the most robust or correct solution, but unlike most of the other solutions, the command works on both Linux and Mac (BSD).



                  host `hostname` | awk '{print $NF}'





                  share|improve this answer































                    -2














                    hostname -I >> file_name 


                    this will do everything you want






                    share|improve this answer


























                    • hostname: invalid option -- 'l'...

                      – jasonwryan
                      Dec 23 '15 at 6:56











                    • That's a capital i. Seems to work fine although it apparently prints IP addresses of all interfaces.

                      – Joe
                      Dec 23 '15 at 7:04











                    • it is proposed in one of the previous answers. Also it does not store the IP in the variable. So what is the point of this answer?

                      – Jakuje
                      Dec 23 '15 at 8:10










                    protected by jasonwryan Dec 23 '15 at 6:59



                    Thank you for your interest in this question.
                    Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                    Would you like to answer one of these unanswered questions instead?














                    21 Answers
                    21






                    active

                    oldest

                    votes








                    21 Answers
                    21






                    active

                    oldest

                    votes









                    active

                    oldest

                    votes






                    active

                    oldest

                    votes









                    30














                    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:



                    ip="$(ifconfig | grep -A 1 'eth0' | tail -1 | cut -d ':' -f 2 | cut -d ' ' -f 1)"


                    In other words, get me the network configuration information, look for eth0, get that line and the next one (-A 1), get only the last line, get the second part of that line when splitting with :, then get the first part of that when splitting with space.






                    share|improve this answer



















                    • 1





                      I added an additional grep to your code to ignore any interface with "eth0:" in it; this now works as I expect (giving only the "eth0" IP address and not any sub-interfaces (eth0:0, eth0:1, etc.): ip="$(ifconfig | grep -v 'eth0:' | grep -A 1 'eth0' | tail -1 | cut -d ':' -f 2 | cut -d ' ' -f 1)"

                      – user32250
                      Feb 12 '13 at 19:49








                    • 5





                      You can skip the first grep by using ifconfig eth0

                      – Bryan Larsen
                      Dec 1 '14 at 16:29






                    • 3





                      ifconfig is deprecated, you should use ip address instead

                      – alexises
                      Dec 23 '15 at 15:42
















                    30














                    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:



                    ip="$(ifconfig | grep -A 1 'eth0' | tail -1 | cut -d ':' -f 2 | cut -d ' ' -f 1)"


                    In other words, get me the network configuration information, look for eth0, get that line and the next one (-A 1), get only the last line, get the second part of that line when splitting with :, then get the first part of that when splitting with space.






                    share|improve this answer



















                    • 1





                      I added an additional grep to your code to ignore any interface with "eth0:" in it; this now works as I expect (giving only the "eth0" IP address and not any sub-interfaces (eth0:0, eth0:1, etc.): ip="$(ifconfig | grep -v 'eth0:' | grep -A 1 'eth0' | tail -1 | cut -d ':' -f 2 | cut -d ' ' -f 1)"

                      – user32250
                      Feb 12 '13 at 19:49








                    • 5





                      You can skip the first grep by using ifconfig eth0

                      – Bryan Larsen
                      Dec 1 '14 at 16:29






                    • 3





                      ifconfig is deprecated, you should use ip address instead

                      – alexises
                      Dec 23 '15 at 15:42














                    30












                    30








                    30







                    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:



                    ip="$(ifconfig | grep -A 1 'eth0' | tail -1 | cut -d ':' -f 2 | cut -d ' ' -f 1)"


                    In other words, get me the network configuration information, look for eth0, get that line and the next one (-A 1), get only the last line, get the second part of that line when splitting with :, then get the first part of that when splitting with space.






                    share|improve this answer













                    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:



                    ip="$(ifconfig | grep -A 1 'eth0' | tail -1 | cut -d ':' -f 2 | cut -d ' ' -f 1)"


                    In other words, get me the network configuration information, look for eth0, get that line and the next one (-A 1), get only the last line, get the second part of that line when splitting with :, then get the first part of that when splitting with space.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Mar 3 '11 at 13:24









                    l0b0l0b0

                    28.9k20122251




                    28.9k20122251








                    • 1





                      I added an additional grep to your code to ignore any interface with "eth0:" in it; this now works as I expect (giving only the "eth0" IP address and not any sub-interfaces (eth0:0, eth0:1, etc.): ip="$(ifconfig | grep -v 'eth0:' | grep -A 1 'eth0' | tail -1 | cut -d ':' -f 2 | cut -d ' ' -f 1)"

                      – user32250
                      Feb 12 '13 at 19:49








                    • 5





                      You can skip the first grep by using ifconfig eth0

                      – Bryan Larsen
                      Dec 1 '14 at 16:29






                    • 3





                      ifconfig is deprecated, you should use ip address instead

                      – alexises
                      Dec 23 '15 at 15:42














                    • 1





                      I added an additional grep to your code to ignore any interface with "eth0:" in it; this now works as I expect (giving only the "eth0" IP address and not any sub-interfaces (eth0:0, eth0:1, etc.): ip="$(ifconfig | grep -v 'eth0:' | grep -A 1 'eth0' | tail -1 | cut -d ':' -f 2 | cut -d ' ' -f 1)"

                      – user32250
                      Feb 12 '13 at 19:49








                    • 5





                      You can skip the first grep by using ifconfig eth0

                      – Bryan Larsen
                      Dec 1 '14 at 16:29






                    • 3





                      ifconfig is deprecated, you should use ip address instead

                      – alexises
                      Dec 23 '15 at 15:42








                    1




                    1





                    I added an additional grep to your code to ignore any interface with "eth0:" in it; this now works as I expect (giving only the "eth0" IP address and not any sub-interfaces (eth0:0, eth0:1, etc.): ip="$(ifconfig | grep -v 'eth0:' | grep -A 1 'eth0' | tail -1 | cut -d ':' -f 2 | cut -d ' ' -f 1)"

                    – user32250
                    Feb 12 '13 at 19:49







                    I added an additional grep to your code to ignore any interface with "eth0:" in it; this now works as I expect (giving only the "eth0" IP address and not any sub-interfaces (eth0:0, eth0:1, etc.): ip="$(ifconfig | grep -v 'eth0:' | grep -A 1 'eth0' | tail -1 | cut -d ':' -f 2 | cut -d ' ' -f 1)"

                    – user32250
                    Feb 12 '13 at 19:49






                    5




                    5





                    You can skip the first grep by using ifconfig eth0

                    – Bryan Larsen
                    Dec 1 '14 at 16:29





                    You can skip the first grep by using ifconfig eth0

                    – Bryan Larsen
                    Dec 1 '14 at 16:29




                    3




                    3





                    ifconfig is deprecated, you should use ip address instead

                    – alexises
                    Dec 23 '15 at 15:42





                    ifconfig is deprecated, you should use ip address instead

                    – alexises
                    Dec 23 '15 at 15:42













                    63














                    I believe the "modern tools" way to get your ipv4 address is to parse 'ip' rather than 'ifconfig', so it'd be something like:



                    ip4=$(/sbin/ip -o -4 addr list eth0 | awk '{print $4}' | cut -d/ -f1)
                    ip6=$(/sbin/ip -o -6 addr list eth0 | awk '{print $4}' | cut -d/ -f1)


                    or something like that.






                    share|improve this answer





















                    • 4





                      ip is available on all the Red Hat and Fedora distros I've used. ip is part of the iproute2 package (linuxfoundation.org/collaborate/workgroups/networking/iproute2). ifconfig and route are supposedly deprecated, although they continue to be used by a lot of people, particularly in scripts. ip is much more parsable, in my opionion.

                      – jsbillings
                      Mar 3 '11 at 15:13








                    • 3





                      ip is also available on all Debian and Debian based distros I've seen. It's part of the iproute package which is marked as important.

                      – Arrowmaster
                      Mar 3 '11 at 23:43






                    • 2





                      This is absolutely how it should be done, I would downvote the other answers for their use of ifconfig. ip is part of the iproute2 package which is many a distro by default. It's in most good repos to. en.wikipedia.org/wiki/Iproute2

                      – jwbensley
                      Sep 15 '12 at 12:13








                    • 3





                      @jsbillings Why /sbin/ip instead of ip?

                      – l0b0
                      Jan 15 '13 at 13:02






                    • 1





                      This is an excellent answer! The combination of awk and cut is mildly amusing to me, here's a possible alternative which may not actually be better: ip -o -4 addr show eth0 | awk '{ split($4, ip_addr, "/"); print ip_addr[1] }'

                      – Swiss
                      Jun 15 '17 at 21:21
















                    63














                    I believe the "modern tools" way to get your ipv4 address is to parse 'ip' rather than 'ifconfig', so it'd be something like:



                    ip4=$(/sbin/ip -o -4 addr list eth0 | awk '{print $4}' | cut -d/ -f1)
                    ip6=$(/sbin/ip -o -6 addr list eth0 | awk '{print $4}' | cut -d/ -f1)


                    or something like that.






                    share|improve this answer





















                    • 4





                      ip is available on all the Red Hat and Fedora distros I've used. ip is part of the iproute2 package (linuxfoundation.org/collaborate/workgroups/networking/iproute2). ifconfig and route are supposedly deprecated, although they continue to be used by a lot of people, particularly in scripts. ip is much more parsable, in my opionion.

                      – jsbillings
                      Mar 3 '11 at 15:13








                    • 3





                      ip is also available on all Debian and Debian based distros I've seen. It's part of the iproute package which is marked as important.

                      – Arrowmaster
                      Mar 3 '11 at 23:43






                    • 2





                      This is absolutely how it should be done, I would downvote the other answers for their use of ifconfig. ip is part of the iproute2 package which is many a distro by default. It's in most good repos to. en.wikipedia.org/wiki/Iproute2

                      – jwbensley
                      Sep 15 '12 at 12:13








                    • 3





                      @jsbillings Why /sbin/ip instead of ip?

                      – l0b0
                      Jan 15 '13 at 13:02






                    • 1





                      This is an excellent answer! The combination of awk and cut is mildly amusing to me, here's a possible alternative which may not actually be better: ip -o -4 addr show eth0 | awk '{ split($4, ip_addr, "/"); print ip_addr[1] }'

                      – Swiss
                      Jun 15 '17 at 21:21














                    63












                    63








                    63







                    I believe the "modern tools" way to get your ipv4 address is to parse 'ip' rather than 'ifconfig', so it'd be something like:



                    ip4=$(/sbin/ip -o -4 addr list eth0 | awk '{print $4}' | cut -d/ -f1)
                    ip6=$(/sbin/ip -o -6 addr list eth0 | awk '{print $4}' | cut -d/ -f1)


                    or something like that.






                    share|improve this answer















                    I believe the "modern tools" way to get your ipv4 address is to parse 'ip' rather than 'ifconfig', so it'd be something like:



                    ip4=$(/sbin/ip -o -4 addr list eth0 | awk '{print $4}' | cut -d/ -f1)
                    ip6=$(/sbin/ip -o -6 addr list eth0 | awk '{print $4}' | cut -d/ -f1)


                    or something like that.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Jan 2 '18 at 22:23









                    Chris F Carroll

                    1034




                    1034










                    answered Mar 3 '11 at 13:52









                    jsbillingsjsbillings

                    16.8k34450




                    16.8k34450








                    • 4





                      ip is available on all the Red Hat and Fedora distros I've used. ip is part of the iproute2 package (linuxfoundation.org/collaborate/workgroups/networking/iproute2). ifconfig and route are supposedly deprecated, although they continue to be used by a lot of people, particularly in scripts. ip is much more parsable, in my opionion.

                      – jsbillings
                      Mar 3 '11 at 15:13








                    • 3





                      ip is also available on all Debian and Debian based distros I've seen. It's part of the iproute package which is marked as important.

                      – Arrowmaster
                      Mar 3 '11 at 23:43






                    • 2





                      This is absolutely how it should be done, I would downvote the other answers for their use of ifconfig. ip is part of the iproute2 package which is many a distro by default. It's in most good repos to. en.wikipedia.org/wiki/Iproute2

                      – jwbensley
                      Sep 15 '12 at 12:13








                    • 3





                      @jsbillings Why /sbin/ip instead of ip?

                      – l0b0
                      Jan 15 '13 at 13:02






                    • 1





                      This is an excellent answer! The combination of awk and cut is mildly amusing to me, here's a possible alternative which may not actually be better: ip -o -4 addr show eth0 | awk '{ split($4, ip_addr, "/"); print ip_addr[1] }'

                      – Swiss
                      Jun 15 '17 at 21:21














                    • 4





                      ip is available on all the Red Hat and Fedora distros I've used. ip is part of the iproute2 package (linuxfoundation.org/collaborate/workgroups/networking/iproute2). ifconfig and route are supposedly deprecated, although they continue to be used by a lot of people, particularly in scripts. ip is much more parsable, in my opionion.

                      – jsbillings
                      Mar 3 '11 at 15:13








                    • 3





                      ip is also available on all Debian and Debian based distros I've seen. It's part of the iproute package which is marked as important.

                      – Arrowmaster
                      Mar 3 '11 at 23:43






                    • 2





                      This is absolutely how it should be done, I would downvote the other answers for their use of ifconfig. ip is part of the iproute2 package which is many a distro by default. It's in most good repos to. en.wikipedia.org/wiki/Iproute2

                      – jwbensley
                      Sep 15 '12 at 12:13








                    • 3





                      @jsbillings Why /sbin/ip instead of ip?

                      – l0b0
                      Jan 15 '13 at 13:02






                    • 1





                      This is an excellent answer! The combination of awk and cut is mildly amusing to me, here's a possible alternative which may not actually be better: ip -o -4 addr show eth0 | awk '{ split($4, ip_addr, "/"); print ip_addr[1] }'

                      – Swiss
                      Jun 15 '17 at 21:21








                    4




                    4





                    ip is available on all the Red Hat and Fedora distros I've used. ip is part of the iproute2 package (linuxfoundation.org/collaborate/workgroups/networking/iproute2). ifconfig and route are supposedly deprecated, although they continue to be used by a lot of people, particularly in scripts. ip is much more parsable, in my opionion.

                    – jsbillings
                    Mar 3 '11 at 15:13







                    ip is available on all the Red Hat and Fedora distros I've used. ip is part of the iproute2 package (linuxfoundation.org/collaborate/workgroups/networking/iproute2). ifconfig and route are supposedly deprecated, although they continue to be used by a lot of people, particularly in scripts. ip is much more parsable, in my opionion.

                    – jsbillings
                    Mar 3 '11 at 15:13






                    3




                    3





                    ip is also available on all Debian and Debian based distros I've seen. It's part of the iproute package which is marked as important.

                    – Arrowmaster
                    Mar 3 '11 at 23:43





                    ip is also available on all Debian and Debian based distros I've seen. It's part of the iproute package which is marked as important.

                    – Arrowmaster
                    Mar 3 '11 at 23:43




                    2




                    2





                    This is absolutely how it should be done, I would downvote the other answers for their use of ifconfig. ip is part of the iproute2 package which is many a distro by default. It's in most good repos to. en.wikipedia.org/wiki/Iproute2

                    – jwbensley
                    Sep 15 '12 at 12:13







                    This is absolutely how it should be done, I would downvote the other answers for their use of ifconfig. ip is part of the iproute2 package which is many a distro by default. It's in most good repos to. en.wikipedia.org/wiki/Iproute2

                    – jwbensley
                    Sep 15 '12 at 12:13






                    3




                    3





                    @jsbillings Why /sbin/ip instead of ip?

                    – l0b0
                    Jan 15 '13 at 13:02





                    @jsbillings Why /sbin/ip instead of ip?

                    – l0b0
                    Jan 15 '13 at 13:02




                    1




                    1





                    This is an excellent answer! The combination of awk and cut is mildly amusing to me, here's a possible alternative which may not actually be better: ip -o -4 addr show eth0 | awk '{ split($4, ip_addr, "/"); print ip_addr[1] }'

                    – Swiss
                    Jun 15 '17 at 21:21





                    This is an excellent answer! The combination of awk and cut is mildly amusing to me, here's a possible alternative which may not actually be better: ip -o -4 addr show eth0 | awk '{ split($4, ip_addr, "/"); print ip_addr[1] }'

                    – Swiss
                    Jun 15 '17 at 21:21











                    30














                    Why not simply do IP=$(hostname -I) ?






                    share|improve this answer





















                    • 3





                      hostname -i gives me just 127.0.0.1, hostname -I gives me the correct IP-Adress...

                      – student
                      Sep 15 '12 at 12:41













                    • @student yes indeed, I have tested it on a machine that has can resolve its hostname, as the manpage says -i Display the network address(es) of the host name. Note that this works only if the host name can be resolved. Avoid using this option; use hostname --all-ip-addresses

                      – Andrei
                      Sep 15 '12 at 12:49













                    • How can I configure my machine to resolve its hostname?

                      – student
                      Sep 15 '12 at 12:58











                    • the easiest way is adding it to /etc/hosts, along with the corresponding IP address

                      – Andrei
                      Sep 16 '12 at 10:06








                    • 3





                      No -I on FreeBSD, but you can use dig +short `hostname -f`

                      – Tigger
                      Jun 3 '15 at 0:07
















                    30














                    Why not simply do IP=$(hostname -I) ?






                    share|improve this answer





















                    • 3





                      hostname -i gives me just 127.0.0.1, hostname -I gives me the correct IP-Adress...

                      – student
                      Sep 15 '12 at 12:41













                    • @student yes indeed, I have tested it on a machine that has can resolve its hostname, as the manpage says -i Display the network address(es) of the host name. Note that this works only if the host name can be resolved. Avoid using this option; use hostname --all-ip-addresses

                      – Andrei
                      Sep 15 '12 at 12:49













                    • How can I configure my machine to resolve its hostname?

                      – student
                      Sep 15 '12 at 12:58











                    • the easiest way is adding it to /etc/hosts, along with the corresponding IP address

                      – Andrei
                      Sep 16 '12 at 10:06








                    • 3





                      No -I on FreeBSD, but you can use dig +short `hostname -f`

                      – Tigger
                      Jun 3 '15 at 0:07














                    30












                    30








                    30







                    Why not simply do IP=$(hostname -I) ?






                    share|improve this answer















                    Why not simply do IP=$(hostname -I) ?







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Sep 16 '12 at 10:08

























                    answered Sep 15 '12 at 10:20









                    AndreiAndrei

                    74911017




                    74911017








                    • 3





                      hostname -i gives me just 127.0.0.1, hostname -I gives me the correct IP-Adress...

                      – student
                      Sep 15 '12 at 12:41













                    • @student yes indeed, I have tested it on a machine that has can resolve its hostname, as the manpage says -i Display the network address(es) of the host name. Note that this works only if the host name can be resolved. Avoid using this option; use hostname --all-ip-addresses

                      – Andrei
                      Sep 15 '12 at 12:49













                    • How can I configure my machine to resolve its hostname?

                      – student
                      Sep 15 '12 at 12:58











                    • the easiest way is adding it to /etc/hosts, along with the corresponding IP address

                      – Andrei
                      Sep 16 '12 at 10:06








                    • 3





                      No -I on FreeBSD, but you can use dig +short `hostname -f`

                      – Tigger
                      Jun 3 '15 at 0:07














                    • 3





                      hostname -i gives me just 127.0.0.1, hostname -I gives me the correct IP-Adress...

                      – student
                      Sep 15 '12 at 12:41













                    • @student yes indeed, I have tested it on a machine that has can resolve its hostname, as the manpage says -i Display the network address(es) of the host name. Note that this works only if the host name can be resolved. Avoid using this option; use hostname --all-ip-addresses

                      – Andrei
                      Sep 15 '12 at 12:49













                    • How can I configure my machine to resolve its hostname?

                      – student
                      Sep 15 '12 at 12:58











                    • the easiest way is adding it to /etc/hosts, along with the corresponding IP address

                      – Andrei
                      Sep 16 '12 at 10:06








                    • 3





                      No -I on FreeBSD, but you can use dig +short `hostname -f`

                      – Tigger
                      Jun 3 '15 at 0:07








                    3




                    3





                    hostname -i gives me just 127.0.0.1, hostname -I gives me the correct IP-Adress...

                    – student
                    Sep 15 '12 at 12:41







                    hostname -i gives me just 127.0.0.1, hostname -I gives me the correct IP-Adress...

                    – student
                    Sep 15 '12 at 12:41















                    @student yes indeed, I have tested it on a machine that has can resolve its hostname, as the manpage says -i Display the network address(es) of the host name. Note that this works only if the host name can be resolved. Avoid using this option; use hostname --all-ip-addresses

                    – Andrei
                    Sep 15 '12 at 12:49







                    @student yes indeed, I have tested it on a machine that has can resolve its hostname, as the manpage says -i Display the network address(es) of the host name. Note that this works only if the host name can be resolved. Avoid using this option; use hostname --all-ip-addresses

                    – Andrei
                    Sep 15 '12 at 12:49















                    How can I configure my machine to resolve its hostname?

                    – student
                    Sep 15 '12 at 12:58





                    How can I configure my machine to resolve its hostname?

                    – student
                    Sep 15 '12 at 12:58













                    the easiest way is adding it to /etc/hosts, along with the corresponding IP address

                    – Andrei
                    Sep 16 '12 at 10:06







                    the easiest way is adding it to /etc/hosts, along with the corresponding IP address

                    – Andrei
                    Sep 16 '12 at 10:06






                    3




                    3





                    No -I on FreeBSD, but you can use dig +short `hostname -f`

                    – Tigger
                    Jun 3 '15 at 0:07





                    No -I on FreeBSD, but you can use dig +short `hostname -f`

                    – Tigger
                    Jun 3 '15 at 0:07











                    23














                    If you want the address of an interface, the easiest way is to install moreutils then:



                    anthony@Zia:~$ ifdata -pa br0
                    172.16.1.244


                    ifdata answers pretty much every question you'd be tempted to parse ifconfig output for.



                    If you want to find out your IP address as the outside sees it (beyond any NAT, etc.), there are plenty of services that'll do it. One is fairly easy:



                    anthony@Zia:~$ curl ifconfig.me
                    173.167.51.137





                    share|improve this answer
























                    • Oh goodness, thank you for this answer. Never heard of moreutils before. I was seriously considering writing my own little C program to do exactly that.

                      – Chris Harrington
                      Feb 28 '16 at 2:02











                    • It would be nice to have ifdata added into iproute2. Maybe a new binary called ipdata

                      – Swiss
                      Jun 15 '17 at 21:25













                    • ifdata is good BUT it doesn't supports ipv6.

                      – BringBackCommodore64
                      Jul 6 '17 at 11:29


















                    23














                    If you want the address of an interface, the easiest way is to install moreutils then:



                    anthony@Zia:~$ ifdata -pa br0
                    172.16.1.244


                    ifdata answers pretty much every question you'd be tempted to parse ifconfig output for.



                    If you want to find out your IP address as the outside sees it (beyond any NAT, etc.), there are plenty of services that'll do it. One is fairly easy:



                    anthony@Zia:~$ curl ifconfig.me
                    173.167.51.137





                    share|improve this answer
























                    • Oh goodness, thank you for this answer. Never heard of moreutils before. I was seriously considering writing my own little C program to do exactly that.

                      – Chris Harrington
                      Feb 28 '16 at 2:02











                    • It would be nice to have ifdata added into iproute2. Maybe a new binary called ipdata

                      – Swiss
                      Jun 15 '17 at 21:25













                    • ifdata is good BUT it doesn't supports ipv6.

                      – BringBackCommodore64
                      Jul 6 '17 at 11:29
















                    23












                    23








                    23







                    If you want the address of an interface, the easiest way is to install moreutils then:



                    anthony@Zia:~$ ifdata -pa br0
                    172.16.1.244


                    ifdata answers pretty much every question you'd be tempted to parse ifconfig output for.



                    If you want to find out your IP address as the outside sees it (beyond any NAT, etc.), there are plenty of services that'll do it. One is fairly easy:



                    anthony@Zia:~$ curl ifconfig.me
                    173.167.51.137





                    share|improve this answer













                    If you want the address of an interface, the easiest way is to install moreutils then:



                    anthony@Zia:~$ ifdata -pa br0
                    172.16.1.244


                    ifdata answers pretty much every question you'd be tempted to parse ifconfig output for.



                    If you want to find out your IP address as the outside sees it (beyond any NAT, etc.), there are plenty of services that'll do it. One is fairly easy:



                    anthony@Zia:~$ curl ifconfig.me
                    173.167.51.137






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Jul 24 '13 at 14:38









                    derobertderobert

                    75.5k8164223




                    75.5k8164223













                    • Oh goodness, thank you for this answer. Never heard of moreutils before. I was seriously considering writing my own little C program to do exactly that.

                      – Chris Harrington
                      Feb 28 '16 at 2:02











                    • It would be nice to have ifdata added into iproute2. Maybe a new binary called ipdata

                      – Swiss
                      Jun 15 '17 at 21:25













                    • ifdata is good BUT it doesn't supports ipv6.

                      – BringBackCommodore64
                      Jul 6 '17 at 11:29





















                    • Oh goodness, thank you for this answer. Never heard of moreutils before. I was seriously considering writing my own little C program to do exactly that.

                      – Chris Harrington
                      Feb 28 '16 at 2:02











                    • It would be nice to have ifdata added into iproute2. Maybe a new binary called ipdata

                      – Swiss
                      Jun 15 '17 at 21:25













                    • ifdata is good BUT it doesn't supports ipv6.

                      – BringBackCommodore64
                      Jul 6 '17 at 11:29



















                    Oh goodness, thank you for this answer. Never heard of moreutils before. I was seriously considering writing my own little C program to do exactly that.

                    – Chris Harrington
                    Feb 28 '16 at 2:02





                    Oh goodness, thank you for this answer. Never heard of moreutils before. I was seriously considering writing my own little C program to do exactly that.

                    – Chris Harrington
                    Feb 28 '16 at 2:02













                    It would be nice to have ifdata added into iproute2. Maybe a new binary called ipdata

                    – Swiss
                    Jun 15 '17 at 21:25







                    It would be nice to have ifdata added into iproute2. Maybe a new binary called ipdata

                    – Swiss
                    Jun 15 '17 at 21:25















                    ifdata is good BUT it doesn't supports ipv6.

                    – BringBackCommodore64
                    Jul 6 '17 at 11:29







                    ifdata is good BUT it doesn't supports ipv6.

                    – BringBackCommodore64
                    Jul 6 '17 at 11:29













                    11














                    To get IPv4 and IPv6 addresses, and not assume the main interface is eth0 (these days em1 is more common), try:



                    ips=$(ip -o addr show up primary scope global |
                    while read -r num dev fam addr rest; do echo ${addr%/*}; done)




                    • -o uses the one-line output format, which is easier to process with read, grep, etc.


                    • up excludes devices that aren't active


                    • scope global excludes private/local addresses such as 127.0.0.1 and fe80::/64


                    • primary excludes temporary addresses (assuming you want an address that doesn't change)






                    share|improve this answer



















                    • 1





                      This has to be the best answer because 1) it doesn't assumes a device name, 2) it uses 'ip' as opposed to old school 'ifconfig', and 3) it supports ipv6 as well.

                      – BringBackCommodore64
                      Jul 6 '17 at 11:31













                    • I agreed, it the best start for most use cases. You can pass -4/-6 to filter address types. You can also easily get other interface parameters. Personally, I dislike while loop and I prefer grep -o 'inet6? [0-9a-f.:]*' | cut -f 2 -d ' '

                      – Jezz
                      May 18 '18 at 7:42
















                    11














                    To get IPv4 and IPv6 addresses, and not assume the main interface is eth0 (these days em1 is more common), try:



                    ips=$(ip -o addr show up primary scope global |
                    while read -r num dev fam addr rest; do echo ${addr%/*}; done)




                    • -o uses the one-line output format, which is easier to process with read, grep, etc.


                    • up excludes devices that aren't active


                    • scope global excludes private/local addresses such as 127.0.0.1 and fe80::/64


                    • primary excludes temporary addresses (assuming you want an address that doesn't change)






                    share|improve this answer



















                    • 1





                      This has to be the best answer because 1) it doesn't assumes a device name, 2) it uses 'ip' as opposed to old school 'ifconfig', and 3) it supports ipv6 as well.

                      – BringBackCommodore64
                      Jul 6 '17 at 11:31













                    • I agreed, it the best start for most use cases. You can pass -4/-6 to filter address types. You can also easily get other interface parameters. Personally, I dislike while loop and I prefer grep -o 'inet6? [0-9a-f.:]*' | cut -f 2 -d ' '

                      – Jezz
                      May 18 '18 at 7:42














                    11












                    11








                    11







                    To get IPv4 and IPv6 addresses, and not assume the main interface is eth0 (these days em1 is more common), try:



                    ips=$(ip -o addr show up primary scope global |
                    while read -r num dev fam addr rest; do echo ${addr%/*}; done)




                    • -o uses the one-line output format, which is easier to process with read, grep, etc.


                    • up excludes devices that aren't active


                    • scope global excludes private/local addresses such as 127.0.0.1 and fe80::/64


                    • primary excludes temporary addresses (assuming you want an address that doesn't change)






                    share|improve this answer













                    To get IPv4 and IPv6 addresses, and not assume the main interface is eth0 (these days em1 is more common), try:



                    ips=$(ip -o addr show up primary scope global |
                    while read -r num dev fam addr rest; do echo ${addr%/*}; done)




                    • -o uses the one-line output format, which is easier to process with read, grep, etc.


                    • up excludes devices that aren't active


                    • scope global excludes private/local addresses such as 127.0.0.1 and fe80::/64


                    • primary excludes temporary addresses (assuming you want an address that doesn't change)







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Jun 3 '15 at 0:27









                    MikelMikel

                    40.4k10103128




                    40.4k10103128








                    • 1





                      This has to be the best answer because 1) it doesn't assumes a device name, 2) it uses 'ip' as opposed to old school 'ifconfig', and 3) it supports ipv6 as well.

                      – BringBackCommodore64
                      Jul 6 '17 at 11:31













                    • I agreed, it the best start for most use cases. You can pass -4/-6 to filter address types. You can also easily get other interface parameters. Personally, I dislike while loop and I prefer grep -o 'inet6? [0-9a-f.:]*' | cut -f 2 -d ' '

                      – Jezz
                      May 18 '18 at 7:42














                    • 1





                      This has to be the best answer because 1) it doesn't assumes a device name, 2) it uses 'ip' as opposed to old school 'ifconfig', and 3) it supports ipv6 as well.

                      – BringBackCommodore64
                      Jul 6 '17 at 11:31













                    • I agreed, it the best start for most use cases. You can pass -4/-6 to filter address types. You can also easily get other interface parameters. Personally, I dislike while loop and I prefer grep -o 'inet6? [0-9a-f.:]*' | cut -f 2 -d ' '

                      – Jezz
                      May 18 '18 at 7:42








                    1




                    1





                    This has to be the best answer because 1) it doesn't assumes a device name, 2) it uses 'ip' as opposed to old school 'ifconfig', and 3) it supports ipv6 as well.

                    – BringBackCommodore64
                    Jul 6 '17 at 11:31







                    This has to be the best answer because 1) it doesn't assumes a device name, 2) it uses 'ip' as opposed to old school 'ifconfig', and 3) it supports ipv6 as well.

                    – BringBackCommodore64
                    Jul 6 '17 at 11:31















                    I agreed, it the best start for most use cases. You can pass -4/-6 to filter address types. You can also easily get other interface parameters. Personally, I dislike while loop and I prefer grep -o 'inet6? [0-9a-f.:]*' | cut -f 2 -d ' '

                    – Jezz
                    May 18 '18 at 7:42





                    I agreed, it the best start for most use cases. You can pass -4/-6 to filter address types. You can also easily get other interface parameters. Personally, I dislike while loop and I prefer grep -o 'inet6? [0-9a-f.:]*' | cut -f 2 -d ' '

                    – Jezz
                    May 18 '18 at 7:42











                    7














                    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:



                    perl -MSocket -le 'socket(S, PF_INET, SOCK_DGRAM, getprotobyname("udp"));
                    connect(S, sockaddr_in(1, inet_aton("8.8.8.8")));
                    print inet_ntoa((sockaddr_in(getsockname(S)))[1]);'


                    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.






                    share|improve this answer




























                      7














                      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:



                      perl -MSocket -le 'socket(S, PF_INET, SOCK_DGRAM, getprotobyname("udp"));
                      connect(S, sockaddr_in(1, inet_aton("8.8.8.8")));
                      print inet_ntoa((sockaddr_in(getsockname(S)))[1]);'


                      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.






                      share|improve this answer


























                        7












                        7








                        7







                        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:



                        perl -MSocket -le 'socket(S, PF_INET, SOCK_DGRAM, getprotobyname("udp"));
                        connect(S, sockaddr_in(1, inet_aton("8.8.8.8")));
                        print inet_ntoa((sockaddr_in(getsockname(S)))[1]);'


                        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.






                        share|improve this answer













                        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:



                        perl -MSocket -le 'socket(S, PF_INET, SOCK_DGRAM, getprotobyname("udp"));
                        connect(S, sockaddr_in(1, inet_aton("8.8.8.8")));
                        print inet_ntoa((sockaddr_in(getsockname(S)))[1]);'


                        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.







                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Sep 16 '12 at 10:39









                        Stéphane ChazelasStéphane Chazelas

                        315k57599956




                        315k57599956























                            7














                            ipa=$(ip route get 8.8.8.8| grep src| sed 's/.*src (.*)$/1/g')

                            ipa=$(hostname -i|cut -f2 -d ' ')





                            share|improve this answer
























                            • Using -I instead of -i is better as you would want to ignore loopback adresses, so the final command would be ipa=$(hostname -I|cut -f1 -d ' ')

                              – Karl.S
                              Oct 17 '17 at 22:00






                            • 1





                              If grep isn't enough, don't pipe it to something else. Just use the something else (sed, awk, etc.).

                              – Bruno Bronosky
                              Aug 11 '18 at 16:58
















                            7














                            ipa=$(ip route get 8.8.8.8| grep src| sed 's/.*src (.*)$/1/g')

                            ipa=$(hostname -i|cut -f2 -d ' ')





                            share|improve this answer
























                            • Using -I instead of -i is better as you would want to ignore loopback adresses, so the final command would be ipa=$(hostname -I|cut -f1 -d ' ')

                              – Karl.S
                              Oct 17 '17 at 22:00






                            • 1





                              If grep isn't enough, don't pipe it to something else. Just use the something else (sed, awk, etc.).

                              – Bruno Bronosky
                              Aug 11 '18 at 16:58














                            7












                            7








                            7







                            ipa=$(ip route get 8.8.8.8| grep src| sed 's/.*src (.*)$/1/g')

                            ipa=$(hostname -i|cut -f2 -d ' ')





                            share|improve this answer













                            ipa=$(ip route get 8.8.8.8| grep src| sed 's/.*src (.*)$/1/g')

                            ipa=$(hostname -i|cut -f2 -d ' ')






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Sep 17 '15 at 21:45









                            fastrizwaanfastrizwaan

                            11914




                            11914













                            • Using -I instead of -i is better as you would want to ignore loopback adresses, so the final command would be ipa=$(hostname -I|cut -f1 -d ' ')

                              – Karl.S
                              Oct 17 '17 at 22:00






                            • 1





                              If grep isn't enough, don't pipe it to something else. Just use the something else (sed, awk, etc.).

                              – Bruno Bronosky
                              Aug 11 '18 at 16:58



















                            • Using -I instead of -i is better as you would want to ignore loopback adresses, so the final command would be ipa=$(hostname -I|cut -f1 -d ' ')

                              – Karl.S
                              Oct 17 '17 at 22:00






                            • 1





                              If grep isn't enough, don't pipe it to something else. Just use the something else (sed, awk, etc.).

                              – Bruno Bronosky
                              Aug 11 '18 at 16:58

















                            Using -I instead of -i is better as you would want to ignore loopback adresses, so the final command would be ipa=$(hostname -I|cut -f1 -d ' ')

                            – Karl.S
                            Oct 17 '17 at 22:00





                            Using -I instead of -i is better as you would want to ignore loopback adresses, so the final command would be ipa=$(hostname -I|cut -f1 -d ' ')

                            – Karl.S
                            Oct 17 '17 at 22:00




                            1




                            1





                            If grep isn't enough, don't pipe it to something else. Just use the something else (sed, awk, etc.).

                            – Bruno Bronosky
                            Aug 11 '18 at 16:58





                            If grep isn't enough, don't pipe it to something else. Just use the something else (sed, awk, etc.).

                            – Bruno Bronosky
                            Aug 11 '18 at 16:58











                            7














                            I don't mean to be a jerk, but there really is a right way and this is it. You trim the output of ip route to get only the source IP. Depending on what IP you are trying to reach, "my own ip address" (OP's words) will be different. If you care about reaching the public internet, using Google's 8.8.8.8 DNS server is pretty standard. So...



                            The short answer is:



                            ip route get 8.8.8.8 | sed -n '/src/{s/.*src *//p;q}'


                            Here's the detailed explanation



                            If I want the ip I use to reach the internet, I use this:



                            pi@et3:~ $ ip route get 8.8.8.8 | sed -n '/src/{s/.*src *//p;q}'
                            10.55.0.200


                            If I want the ip I use to reach something on my VPN, I use this:



                            pi@et3:~ $ ip route get 172.31.0.100 | sed -n '/src/{s/.*src *//p;q}'
                            172.29.0.9



                            This next one is really just for illustrative purposes. But, it should work on any Linux system. So, you can use this to demonstrate that, yes, all machines have multiple IP addresses at all times.




                            If I wanted the ip I use to reach myself, I would use this:



                            pi@et3:~ $ my_ip=$(getent hosts $(cat /etc/hostname) | awk '{print $1; exit}')
                            pi@et3:~ $ ip route get $my_ip | sed -n '/src/{s/.*src *//p;q}'
                            127.0.0.1


                            More about that sed command



                            First let me say that when choosing unix tools, you try to choose the tools that require the fewest pipes. So, while some answers will pipe ifconfig to grep to sed to head, that is rarely ever necessary. When you see it, it should raise a red flag that you are taking advice from someone with little experience. That doesn't make the "solution" wrong. But, it probably could use some streamlining.



                            I have chosen sed because it is more terse than the same workflow in awk. I don't think any other tool but those 2 would be appropriate.



                            Let's examine what sed -n '/src/{s/.*src *//p;q}' does:



                            sed            # the sed executable located via $PATH
                            -n # no output unless explicitly requested
                            ' # begin the command space
                            /src/ # regex match the string 'src'
                            { # begin a block of commands **
                            s/.*src *// # regex match "anything followed by 'src' followed by any number of spaces" and replace it with "nothing"
                            p # print (explicitly, remember) the result
                            ; # designate the end of the command
                            q # quit
                            } # end the block of commands
                            ' # end the command space

                            ** all of which will be performed "on match"
                            - otherwise only the first command to following the match would be performed "on match"
                            - any other commands would be performed whether there was a match or not


                            More about my network



                            My ifconfig shows that I have tun0 for my VPN and eth0 for my lan.



                            pi@et3:~ $ ifconfig
                            eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
                            inet 10.55.0.200 netmask 255.255.252.0 broadcast 10.55.3.255
                            inet6 fe80::71e6:5d7c:5b4b:fb25 prefixlen 64 scopeid 0x20<link>
                            ether b8:27:eb:b2:96:84 txqueuelen 1000 (Ethernet)

                            lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
                            inet 127.0.0.1 netmask 255.0.0.0
                            inet6 ::1 prefixlen 128 scopeid 0x10<host>
                            loop txqueuelen 1 (Local Loopback)

                            tun0: flags=4305<UP,POINTOPOINT,RUNNING,NOARP,MULTICAST> mtu 1500
                            inet 172.29.0.9 netmask 255.255.255.255 destination 172.29.0.10
                            inet6 fe80::3a8e:8195:b86c:c68c prefixlen 64 scopeid 0x20<link>
                            unspec 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00 txqueuelen 100 (UNSPEC)

                            wlan0: flags=4099<UP,BROADCAST,MULTICAST> mtu 1500
                            ether b8:27:eb:e7:c3:d1 txqueuelen 1000 (Ethernet)





                            share|improve this answer
























                            • ip route get 8.8.8.8 | sed -n '/src/{s/.*src *//p;q}' gave me 10.1.2.3 uid 1002. So I add to append | awk '{print $1}' to keep only the IP address.

                              – wisbucky
                              4 hours ago
















                            7














                            I don't mean to be a jerk, but there really is a right way and this is it. You trim the output of ip route to get only the source IP. Depending on what IP you are trying to reach, "my own ip address" (OP's words) will be different. If you care about reaching the public internet, using Google's 8.8.8.8 DNS server is pretty standard. So...



                            The short answer is:



                            ip route get 8.8.8.8 | sed -n '/src/{s/.*src *//p;q}'


                            Here's the detailed explanation



                            If I want the ip I use to reach the internet, I use this:



                            pi@et3:~ $ ip route get 8.8.8.8 | sed -n '/src/{s/.*src *//p;q}'
                            10.55.0.200


                            If I want the ip I use to reach something on my VPN, I use this:



                            pi@et3:~ $ ip route get 172.31.0.100 | sed -n '/src/{s/.*src *//p;q}'
                            172.29.0.9



                            This next one is really just for illustrative purposes. But, it should work on any Linux system. So, you can use this to demonstrate that, yes, all machines have multiple IP addresses at all times.




                            If I wanted the ip I use to reach myself, I would use this:



                            pi@et3:~ $ my_ip=$(getent hosts $(cat /etc/hostname) | awk '{print $1; exit}')
                            pi@et3:~ $ ip route get $my_ip | sed -n '/src/{s/.*src *//p;q}'
                            127.0.0.1


                            More about that sed command



                            First let me say that when choosing unix tools, you try to choose the tools that require the fewest pipes. So, while some answers will pipe ifconfig to grep to sed to head, that is rarely ever necessary. When you see it, it should raise a red flag that you are taking advice from someone with little experience. That doesn't make the "solution" wrong. But, it probably could use some streamlining.



                            I have chosen sed because it is more terse than the same workflow in awk. I don't think any other tool but those 2 would be appropriate.



                            Let's examine what sed -n '/src/{s/.*src *//p;q}' does:



                            sed            # the sed executable located via $PATH
                            -n # no output unless explicitly requested
                            ' # begin the command space
                            /src/ # regex match the string 'src'
                            { # begin a block of commands **
                            s/.*src *// # regex match "anything followed by 'src' followed by any number of spaces" and replace it with "nothing"
                            p # print (explicitly, remember) the result
                            ; # designate the end of the command
                            q # quit
                            } # end the block of commands
                            ' # end the command space

                            ** all of which will be performed "on match"
                            - otherwise only the first command to following the match would be performed "on match"
                            - any other commands would be performed whether there was a match or not


                            More about my network



                            My ifconfig shows that I have tun0 for my VPN and eth0 for my lan.



                            pi@et3:~ $ ifconfig
                            eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
                            inet 10.55.0.200 netmask 255.255.252.0 broadcast 10.55.3.255
                            inet6 fe80::71e6:5d7c:5b4b:fb25 prefixlen 64 scopeid 0x20<link>
                            ether b8:27:eb:b2:96:84 txqueuelen 1000 (Ethernet)

                            lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
                            inet 127.0.0.1 netmask 255.0.0.0
                            inet6 ::1 prefixlen 128 scopeid 0x10<host>
                            loop txqueuelen 1 (Local Loopback)

                            tun0: flags=4305<UP,POINTOPOINT,RUNNING,NOARP,MULTICAST> mtu 1500
                            inet 172.29.0.9 netmask 255.255.255.255 destination 172.29.0.10
                            inet6 fe80::3a8e:8195:b86c:c68c prefixlen 64 scopeid 0x20<link>
                            unspec 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00 txqueuelen 100 (UNSPEC)

                            wlan0: flags=4099<UP,BROADCAST,MULTICAST> mtu 1500
                            ether b8:27:eb:e7:c3:d1 txqueuelen 1000 (Ethernet)





                            share|improve this answer
























                            • ip route get 8.8.8.8 | sed -n '/src/{s/.*src *//p;q}' gave me 10.1.2.3 uid 1002. So I add to append | awk '{print $1}' to keep only the IP address.

                              – wisbucky
                              4 hours ago














                            7












                            7








                            7







                            I don't mean to be a jerk, but there really is a right way and this is it. You trim the output of ip route to get only the source IP. Depending on what IP you are trying to reach, "my own ip address" (OP's words) will be different. If you care about reaching the public internet, using Google's 8.8.8.8 DNS server is pretty standard. So...



                            The short answer is:



                            ip route get 8.8.8.8 | sed -n '/src/{s/.*src *//p;q}'


                            Here's the detailed explanation



                            If I want the ip I use to reach the internet, I use this:



                            pi@et3:~ $ ip route get 8.8.8.8 | sed -n '/src/{s/.*src *//p;q}'
                            10.55.0.200


                            If I want the ip I use to reach something on my VPN, I use this:



                            pi@et3:~ $ ip route get 172.31.0.100 | sed -n '/src/{s/.*src *//p;q}'
                            172.29.0.9



                            This next one is really just for illustrative purposes. But, it should work on any Linux system. So, you can use this to demonstrate that, yes, all machines have multiple IP addresses at all times.




                            If I wanted the ip I use to reach myself, I would use this:



                            pi@et3:~ $ my_ip=$(getent hosts $(cat /etc/hostname) | awk '{print $1; exit}')
                            pi@et3:~ $ ip route get $my_ip | sed -n '/src/{s/.*src *//p;q}'
                            127.0.0.1


                            More about that sed command



                            First let me say that when choosing unix tools, you try to choose the tools that require the fewest pipes. So, while some answers will pipe ifconfig to grep to sed to head, that is rarely ever necessary. When you see it, it should raise a red flag that you are taking advice from someone with little experience. That doesn't make the "solution" wrong. But, it probably could use some streamlining.



                            I have chosen sed because it is more terse than the same workflow in awk. I don't think any other tool but those 2 would be appropriate.



                            Let's examine what sed -n '/src/{s/.*src *//p;q}' does:



                            sed            # the sed executable located via $PATH
                            -n # no output unless explicitly requested
                            ' # begin the command space
                            /src/ # regex match the string 'src'
                            { # begin a block of commands **
                            s/.*src *// # regex match "anything followed by 'src' followed by any number of spaces" and replace it with "nothing"
                            p # print (explicitly, remember) the result
                            ; # designate the end of the command
                            q # quit
                            } # end the block of commands
                            ' # end the command space

                            ** all of which will be performed "on match"
                            - otherwise only the first command to following the match would be performed "on match"
                            - any other commands would be performed whether there was a match or not


                            More about my network



                            My ifconfig shows that I have tun0 for my VPN and eth0 for my lan.



                            pi@et3:~ $ ifconfig
                            eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
                            inet 10.55.0.200 netmask 255.255.252.0 broadcast 10.55.3.255
                            inet6 fe80::71e6:5d7c:5b4b:fb25 prefixlen 64 scopeid 0x20<link>
                            ether b8:27:eb:b2:96:84 txqueuelen 1000 (Ethernet)

                            lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
                            inet 127.0.0.1 netmask 255.0.0.0
                            inet6 ::1 prefixlen 128 scopeid 0x10<host>
                            loop txqueuelen 1 (Local Loopback)

                            tun0: flags=4305<UP,POINTOPOINT,RUNNING,NOARP,MULTICAST> mtu 1500
                            inet 172.29.0.9 netmask 255.255.255.255 destination 172.29.0.10
                            inet6 fe80::3a8e:8195:b86c:c68c prefixlen 64 scopeid 0x20<link>
                            unspec 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00 txqueuelen 100 (UNSPEC)

                            wlan0: flags=4099<UP,BROADCAST,MULTICAST> mtu 1500
                            ether b8:27:eb:e7:c3:d1 txqueuelen 1000 (Ethernet)





                            share|improve this answer













                            I don't mean to be a jerk, but there really is a right way and this is it. You trim the output of ip route to get only the source IP. Depending on what IP you are trying to reach, "my own ip address" (OP's words) will be different. If you care about reaching the public internet, using Google's 8.8.8.8 DNS server is pretty standard. So...



                            The short answer is:



                            ip route get 8.8.8.8 | sed -n '/src/{s/.*src *//p;q}'


                            Here's the detailed explanation



                            If I want the ip I use to reach the internet, I use this:



                            pi@et3:~ $ ip route get 8.8.8.8 | sed -n '/src/{s/.*src *//p;q}'
                            10.55.0.200


                            If I want the ip I use to reach something on my VPN, I use this:



                            pi@et3:~ $ ip route get 172.31.0.100 | sed -n '/src/{s/.*src *//p;q}'
                            172.29.0.9



                            This next one is really just for illustrative purposes. But, it should work on any Linux system. So, you can use this to demonstrate that, yes, all machines have multiple IP addresses at all times.




                            If I wanted the ip I use to reach myself, I would use this:



                            pi@et3:~ $ my_ip=$(getent hosts $(cat /etc/hostname) | awk '{print $1; exit}')
                            pi@et3:~ $ ip route get $my_ip | sed -n '/src/{s/.*src *//p;q}'
                            127.0.0.1


                            More about that sed command



                            First let me say that when choosing unix tools, you try to choose the tools that require the fewest pipes. So, while some answers will pipe ifconfig to grep to sed to head, that is rarely ever necessary. When you see it, it should raise a red flag that you are taking advice from someone with little experience. That doesn't make the "solution" wrong. But, it probably could use some streamlining.



                            I have chosen sed because it is more terse than the same workflow in awk. I don't think any other tool but those 2 would be appropriate.



                            Let's examine what sed -n '/src/{s/.*src *//p;q}' does:



                            sed            # the sed executable located via $PATH
                            -n # no output unless explicitly requested
                            ' # begin the command space
                            /src/ # regex match the string 'src'
                            { # begin a block of commands **
                            s/.*src *// # regex match "anything followed by 'src' followed by any number of spaces" and replace it with "nothing"
                            p # print (explicitly, remember) the result
                            ; # designate the end of the command
                            q # quit
                            } # end the block of commands
                            ' # end the command space

                            ** all of which will be performed "on match"
                            - otherwise only the first command to following the match would be performed "on match"
                            - any other commands would be performed whether there was a match or not


                            More about my network



                            My ifconfig shows that I have tun0 for my VPN and eth0 for my lan.



                            pi@et3:~ $ ifconfig
                            eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
                            inet 10.55.0.200 netmask 255.255.252.0 broadcast 10.55.3.255
                            inet6 fe80::71e6:5d7c:5b4b:fb25 prefixlen 64 scopeid 0x20<link>
                            ether b8:27:eb:b2:96:84 txqueuelen 1000 (Ethernet)

                            lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
                            inet 127.0.0.1 netmask 255.0.0.0
                            inet6 ::1 prefixlen 128 scopeid 0x10<host>
                            loop txqueuelen 1 (Local Loopback)

                            tun0: flags=4305<UP,POINTOPOINT,RUNNING,NOARP,MULTICAST> mtu 1500
                            inet 172.29.0.9 netmask 255.255.255.255 destination 172.29.0.10
                            inet6 fe80::3a8e:8195:b86c:c68c prefixlen 64 scopeid 0x20<link>
                            unspec 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00 txqueuelen 100 (UNSPEC)

                            wlan0: flags=4099<UP,BROADCAST,MULTICAST> mtu 1500
                            ether b8:27:eb:e7:c3:d1 txqueuelen 1000 (Ethernet)






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 2 '17 at 21:09









                            Bruno BronoskyBruno Bronosky

                            1,97211313




                            1,97211313













                            • ip route get 8.8.8.8 | sed -n '/src/{s/.*src *//p;q}' gave me 10.1.2.3 uid 1002. So I add to append | awk '{print $1}' to keep only the IP address.

                              – wisbucky
                              4 hours ago



















                            • ip route get 8.8.8.8 | sed -n '/src/{s/.*src *//p;q}' gave me 10.1.2.3 uid 1002. So I add to append | awk '{print $1}' to keep only the IP address.

                              – wisbucky
                              4 hours ago

















                            ip route get 8.8.8.8 | sed -n '/src/{s/.*src *//p;q}' gave me 10.1.2.3 uid 1002. So I add to append | awk '{print $1}' to keep only the IP address.

                            – wisbucky
                            4 hours ago





                            ip route get 8.8.8.8 | sed -n '/src/{s/.*src *//p;q}' gave me 10.1.2.3 uid 1002. So I add to append | awk '{print $1}' to keep only the IP address.

                            – wisbucky
                            4 hours ago











                            2














                            On FreeBSD you can use



                            dig +short `hostname -f`


                            This may work for other environments, depends on your set-up.






                            share|improve this answer
























                            • I believe this is dependant on the configuration of /etc/resolv.conf and how the network router handles local hostnames. It's fine to use this in your environment if you test it and it works. But if you do so, you are building a "brittle" system that is going to cause others problems if you share this. Use with caution.

                              – Bruno Bronosky
                              Apr 1 '18 at 17:28
















                            2














                            On FreeBSD you can use



                            dig +short `hostname -f`


                            This may work for other environments, depends on your set-up.






                            share|improve this answer
























                            • I believe this is dependant on the configuration of /etc/resolv.conf and how the network router handles local hostnames. It's fine to use this in your environment if you test it and it works. But if you do so, you are building a "brittle" system that is going to cause others problems if you share this. Use with caution.

                              – Bruno Bronosky
                              Apr 1 '18 at 17:28














                            2












                            2








                            2







                            On FreeBSD you can use



                            dig +short `hostname -f`


                            This may work for other environments, depends on your set-up.






                            share|improve this answer













                            On FreeBSD you can use



                            dig +short `hostname -f`


                            This may work for other environments, depends on your set-up.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Jun 3 '15 at 0:09









                            TiggerTigger

                            2,1411013




                            2,1411013













                            • I believe this is dependant on the configuration of /etc/resolv.conf and how the network router handles local hostnames. It's fine to use this in your environment if you test it and it works. But if you do so, you are building a "brittle" system that is going to cause others problems if you share this. Use with caution.

                              – Bruno Bronosky
                              Apr 1 '18 at 17:28



















                            • I believe this is dependant on the configuration of /etc/resolv.conf and how the network router handles local hostnames. It's fine to use this in your environment if you test it and it works. But if you do so, you are building a "brittle" system that is going to cause others problems if you share this. Use with caution.

                              – Bruno Bronosky
                              Apr 1 '18 at 17:28

















                            I believe this is dependant on the configuration of /etc/resolv.conf and how the network router handles local hostnames. It's fine to use this in your environment if you test it and it works. But if you do so, you are building a "brittle" system that is going to cause others problems if you share this. Use with caution.

                            – Bruno Bronosky
                            Apr 1 '18 at 17:28





                            I believe this is dependant on the configuration of /etc/resolv.conf and how the network router handles local hostnames. It's fine to use this in your environment if you test it and it works. But if you do so, you are building a "brittle" system that is going to cause others problems if you share this. Use with caution.

                            – Bruno Bronosky
                            Apr 1 '18 at 17:28











                            2














                            Assuming that you may have various interfaces of various name but that you want the first non-localhost one and non-ipv6, you may try:



                            ip=`ip addr show |grep "inet " |grep -v 127.0.0. |head -1|cut -d" " -f6|cut -d/ -f1`





                            share|improve this answer
























                            • ip=$(ifconfig | grep -oP '(?<=inet addr:)S*' | grep -v 127)

                              – rcjohnson
                              Nov 17 '15 at 17:12
















                            2














                            Assuming that you may have various interfaces of various name but that you want the first non-localhost one and non-ipv6, you may try:



                            ip=`ip addr show |grep "inet " |grep -v 127.0.0. |head -1|cut -d" " -f6|cut -d/ -f1`





                            share|improve this answer
























                            • ip=$(ifconfig | grep -oP '(?<=inet addr:)S*' | grep -v 127)

                              – rcjohnson
                              Nov 17 '15 at 17:12














                            2












                            2








                            2







                            Assuming that you may have various interfaces of various name but that you want the first non-localhost one and non-ipv6, you may try:



                            ip=`ip addr show |grep "inet " |grep -v 127.0.0. |head -1|cut -d" " -f6|cut -d/ -f1`





                            share|improve this answer













                            Assuming that you may have various interfaces of various name but that you want the first non-localhost one and non-ipv6, you may try:



                            ip=`ip addr show |grep "inet " |grep -v 127.0.0. |head -1|cut -d" " -f6|cut -d/ -f1`






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 17 '15 at 16:35









                            NicolasNicolas

                            211




                            211













                            • ip=$(ifconfig | grep -oP '(?<=inet addr:)S*' | grep -v 127)

                              – rcjohnson
                              Nov 17 '15 at 17:12



















                            • ip=$(ifconfig | grep -oP '(?<=inet addr:)S*' | grep -v 127)

                              – rcjohnson
                              Nov 17 '15 at 17:12

















                            ip=$(ifconfig | grep -oP '(?<=inet addr:)S*' | grep -v 127)

                            – rcjohnson
                            Nov 17 '15 at 17:12





                            ip=$(ifconfig | grep -oP '(?<=inet addr:)S*' | grep -v 127)

                            – rcjohnson
                            Nov 17 '15 at 17:12











                            1














                            I use this one-liner:



                            IP=$(/sbin/ifconfig | grep -e "inet:" -e "addr:" | grep -v "inet6" | grep -v "127.0.0.1" | head -n 1 | awk '{print $2}' | cut -c6-)


                            Uses ifconfig (widely available), does not take localhost address, does not bind you to a given interface name, does not take into account IPv6 and tries to get the IP of the first network interface available.






                            share|improve this answer




























                              1














                              I use this one-liner:



                              IP=$(/sbin/ifconfig | grep -e "inet:" -e "addr:" | grep -v "inet6" | grep -v "127.0.0.1" | head -n 1 | awk '{print $2}' | cut -c6-)


                              Uses ifconfig (widely available), does not take localhost address, does not bind you to a given interface name, does not take into account IPv6 and tries to get the IP of the first network interface available.






                              share|improve this answer


























                                1












                                1








                                1







                                I use this one-liner:



                                IP=$(/sbin/ifconfig | grep -e "inet:" -e "addr:" | grep -v "inet6" | grep -v "127.0.0.1" | head -n 1 | awk '{print $2}' | cut -c6-)


                                Uses ifconfig (widely available), does not take localhost address, does not bind you to a given interface name, does not take into account IPv6 and tries to get the IP of the first network interface available.






                                share|improve this answer













                                I use this one-liner:



                                IP=$(/sbin/ifconfig | grep -e "inet:" -e "addr:" | grep -v "inet6" | grep -v "127.0.0.1" | head -n 1 | awk '{print $2}' | cut -c6-)


                                Uses ifconfig (widely available), does not take localhost address, does not bind you to a given interface name, does not take into account IPv6 and tries to get the IP of the first network interface available.







                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Mar 3 '11 at 23:34









                                Andrea SpadacciniAndrea Spadaccini

                                290138




                                290138























                                    0














                                    I needed to do this within an alias to start a radio server on my wired NIC. I used



                                    ip addr | egrep -i "inet.+eth1" | awk -F[ /] '{print $6}' | tr -d [:space:]





                                    share|improve this answer
























                                    • egrep is depreciated. Use grep -E instead.

                                      – Yokai
                                      Jan 25 '18 at 9:23
















                                    0














                                    I needed to do this within an alias to start a radio server on my wired NIC. I used



                                    ip addr | egrep -i "inet.+eth1" | awk -F[ /] '{print $6}' | tr -d [:space:]





                                    share|improve this answer
























                                    • egrep is depreciated. Use grep -E instead.

                                      – Yokai
                                      Jan 25 '18 at 9:23














                                    0












                                    0








                                    0







                                    I needed to do this within an alias to start a radio server on my wired NIC. I used



                                    ip addr | egrep -i "inet.+eth1" | awk -F[ /] '{print $6}' | tr -d [:space:]





                                    share|improve this answer













                                    I needed to do this within an alias to start a radio server on my wired NIC. I used



                                    ip addr | egrep -i "inet.+eth1" | awk -F[ /] '{print $6}' | tr -d [:space:]






                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Mar 26 '15 at 1:09









                                    user208145user208145

                                    1,37121316




                                    1,37121316













                                    • egrep is depreciated. Use grep -E instead.

                                      – Yokai
                                      Jan 25 '18 at 9:23



















                                    • egrep is depreciated. Use grep -E instead.

                                      – Yokai
                                      Jan 25 '18 at 9:23

















                                    egrep is depreciated. Use grep -E instead.

                                    – Yokai
                                    Jan 25 '18 at 9:23





                                    egrep is depreciated. Use grep -E instead.

                                    – Yokai
                                    Jan 25 '18 at 9:23











                                    0














                                    Some commands are working on centos 6 or 7, the below command working on both,



                                    #!/bin/sh

                                    serverip=`/sbin/ifconfig eth0 | grep "inet" | awk '{print $2}' | awk 'NR==1' | cut -d':' -f2`

                                    echo $serverip





                                    share|improve this answer
























                                    • that's way too much grep | awk | awk . line can be shortened to /sbin/ifconfig eth0 | awk '$1 == "inet" { print substr($2,6); next ; } '

                                      – Archemar
                                      Aug 6 '15 at 11:23











                                    • I accepted, can you check both centos6 and 7?. centos 7.x /sbin/ifconfig eth0 | awk '$1 == "inet" { print substr($2,6); next ; }' 35.104.41 centos6.x (Working fine) /sbin/ifconfig eth0 | awk '$1 == "inet" { print substr($2,6); next ; }' 192.168.0.1

                                      – lakshmikandan
                                      Aug 7 '15 at 4:32


















                                    0














                                    Some commands are working on centos 6 or 7, the below command working on both,



                                    #!/bin/sh

                                    serverip=`/sbin/ifconfig eth0 | grep "inet" | awk '{print $2}' | awk 'NR==1' | cut -d':' -f2`

                                    echo $serverip





                                    share|improve this answer
























                                    • that's way too much grep | awk | awk . line can be shortened to /sbin/ifconfig eth0 | awk '$1 == "inet" { print substr($2,6); next ; } '

                                      – Archemar
                                      Aug 6 '15 at 11:23











                                    • I accepted, can you check both centos6 and 7?. centos 7.x /sbin/ifconfig eth0 | awk '$1 == "inet" { print substr($2,6); next ; }' 35.104.41 centos6.x (Working fine) /sbin/ifconfig eth0 | awk '$1 == "inet" { print substr($2,6); next ; }' 192.168.0.1

                                      – lakshmikandan
                                      Aug 7 '15 at 4:32
















                                    0












                                    0








                                    0







                                    Some commands are working on centos 6 or 7, the below command working on both,



                                    #!/bin/sh

                                    serverip=`/sbin/ifconfig eth0 | grep "inet" | awk '{print $2}' | awk 'NR==1' | cut -d':' -f2`

                                    echo $serverip





                                    share|improve this answer













                                    Some commands are working on centos 6 or 7, the below command working on both,



                                    #!/bin/sh

                                    serverip=`/sbin/ifconfig eth0 | grep "inet" | awk '{print $2}' | awk 'NR==1' | cut -d':' -f2`

                                    echo $serverip






                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Aug 6 '15 at 11:03









                                    lakshmikandanlakshmikandan

                                    1415




                                    1415













                                    • that's way too much grep | awk | awk . line can be shortened to /sbin/ifconfig eth0 | awk '$1 == "inet" { print substr($2,6); next ; } '

                                      – Archemar
                                      Aug 6 '15 at 11:23











                                    • I accepted, can you check both centos6 and 7?. centos 7.x /sbin/ifconfig eth0 | awk '$1 == "inet" { print substr($2,6); next ; }' 35.104.41 centos6.x (Working fine) /sbin/ifconfig eth0 | awk '$1 == "inet" { print substr($2,6); next ; }' 192.168.0.1

                                      – lakshmikandan
                                      Aug 7 '15 at 4:32





















                                    • that's way too much grep | awk | awk . line can be shortened to /sbin/ifconfig eth0 | awk '$1 == "inet" { print substr($2,6); next ; } '

                                      – Archemar
                                      Aug 6 '15 at 11:23











                                    • I accepted, can you check both centos6 and 7?. centos 7.x /sbin/ifconfig eth0 | awk '$1 == "inet" { print substr($2,6); next ; }' 35.104.41 centos6.x (Working fine) /sbin/ifconfig eth0 | awk '$1 == "inet" { print substr($2,6); next ; }' 192.168.0.1

                                      – lakshmikandan
                                      Aug 7 '15 at 4:32



















                                    that's way too much grep | awk | awk . line can be shortened to /sbin/ifconfig eth0 | awk '$1 == "inet" { print substr($2,6); next ; } '

                                    – Archemar
                                    Aug 6 '15 at 11:23





                                    that's way too much grep | awk | awk . line can be shortened to /sbin/ifconfig eth0 | awk '$1 == "inet" { print substr($2,6); next ; } '

                                    – Archemar
                                    Aug 6 '15 at 11:23













                                    I accepted, can you check both centos6 and 7?. centos 7.x /sbin/ifconfig eth0 | awk '$1 == "inet" { print substr($2,6); next ; }' 35.104.41 centos6.x (Working fine) /sbin/ifconfig eth0 | awk '$1 == "inet" { print substr($2,6); next ; }' 192.168.0.1

                                    – lakshmikandan
                                    Aug 7 '15 at 4:32







                                    I accepted, can you check both centos6 and 7?. centos 7.x /sbin/ifconfig eth0 | awk '$1 == "inet" { print substr($2,6); next ; }' 35.104.41 centos6.x (Working fine) /sbin/ifconfig eth0 | awk '$1 == "inet" { print substr($2,6); next ; }' 192.168.0.1

                                    – lakshmikandan
                                    Aug 7 '15 at 4:32













                                    0














                                    Assuming you need your primary public IP as it seen from the rest of the world, try any of those:



                                    wget http://ipecho.net/plain -O - -q
                                    curl http://icanhazip.com
                                    curl http://ifconfig.me/ip





                                    share|improve this answer




























                                      0














                                      Assuming you need your primary public IP as it seen from the rest of the world, try any of those:



                                      wget http://ipecho.net/plain -O - -q
                                      curl http://icanhazip.com
                                      curl http://ifconfig.me/ip





                                      share|improve this answer


























                                        0












                                        0








                                        0







                                        Assuming you need your primary public IP as it seen from the rest of the world, try any of those:



                                        wget http://ipecho.net/plain -O - -q
                                        curl http://icanhazip.com
                                        curl http://ifconfig.me/ip





                                        share|improve this answer













                                        Assuming you need your primary public IP as it seen from the rest of the world, try any of those:



                                        wget http://ipecho.net/plain -O - -q
                                        curl http://icanhazip.com
                                        curl http://ifconfig.me/ip






                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered Jul 11 '17 at 6:19









                                        PutnikPutnik

                                        4442516




                                        4442516























                                            0














                                            This snippet avoids hard-coding the device name (like 'eth0') and will use ip instead of ifconfig:



                                            /sbin/ip addr | grep 'state UP' -A2 | tail -n1 | awk '{print $2}' | cut -f1  -d'/'


                                            It will return the IP of the first active device listed in the output of ip addr. Depending on your machine, this can be an ipv4 or ipv6 address.



                                            To store it into a variable, use:



                                            ip=$(/sbin/ip addr | grep 'state UP' -A2 | tail -n1 | awk '{print $2}' | cut -f1  -d'/')





                                            share|improve this answer




























                                              0














                                              This snippet avoids hard-coding the device name (like 'eth0') and will use ip instead of ifconfig:



                                              /sbin/ip addr | grep 'state UP' -A2 | tail -n1 | awk '{print $2}' | cut -f1  -d'/'


                                              It will return the IP of the first active device listed in the output of ip addr. Depending on your machine, this can be an ipv4 or ipv6 address.



                                              To store it into a variable, use:



                                              ip=$(/sbin/ip addr | grep 'state UP' -A2 | tail -n1 | awk '{print $2}' | cut -f1  -d'/')





                                              share|improve this answer


























                                                0












                                                0








                                                0







                                                This snippet avoids hard-coding the device name (like 'eth0') and will use ip instead of ifconfig:



                                                /sbin/ip addr | grep 'state UP' -A2 | tail -n1 | awk '{print $2}' | cut -f1  -d'/'


                                                It will return the IP of the first active device listed in the output of ip addr. Depending on your machine, this can be an ipv4 or ipv6 address.



                                                To store it into a variable, use:



                                                ip=$(/sbin/ip addr | grep 'state UP' -A2 | tail -n1 | awk '{print $2}' | cut -f1  -d'/')





                                                share|improve this answer













                                                This snippet avoids hard-coding the device name (like 'eth0') and will use ip instead of ifconfig:



                                                /sbin/ip addr | grep 'state UP' -A2 | tail -n1 | awk '{print $2}' | cut -f1  -d'/'


                                                It will return the IP of the first active device listed in the output of ip addr. Depending on your machine, this can be an ipv4 or ipv6 address.



                                                To store it into a variable, use:



                                                ip=$(/sbin/ip addr | grep 'state UP' -A2 | tail -n1 | awk '{print $2}' | cut -f1  -d'/')






                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Aug 7 '17 at 14:34









                                                Philipp ClaßenPhilipp Claßen

                                                1,47052033




                                                1,47052033























                                                    0














                                                    myip=$(curl -kLs "http://api.ipify.org")


                                                    or



                                                    myip=$(wget -q "http://api.ipify.org" -O -)





                                                    share|improve this answer




























                                                      0














                                                      myip=$(curl -kLs "http://api.ipify.org")


                                                      or



                                                      myip=$(wget -q "http://api.ipify.org" -O -)





                                                      share|improve this answer


























                                                        0












                                                        0








                                                        0







                                                        myip=$(curl -kLs "http://api.ipify.org")


                                                        or



                                                        myip=$(wget -q "http://api.ipify.org" -O -)





                                                        share|improve this answer













                                                        myip=$(curl -kLs "http://api.ipify.org")


                                                        or



                                                        myip=$(wget -q "http://api.ipify.org" -O -)






                                                        share|improve this answer












                                                        share|improve this answer



                                                        share|improve this answer










                                                        answered Aug 7 '17 at 18:33









                                                        ZibriZibri

                                                        16927




                                                        16927























                                                            0














                                                            all the solutions using awk/sed/grep seem overly complex and ugly for my situation... so i came up with this really simple solution BUT beware cus it makes some assumptions, namely the assumption that the LAST interface is the one you're interested. if you're ok with that then this is pretty clean:



                                                            ifconfig | awk '/net / { x = $2 } END { print x }'



                                                            otherwise you could do some silly if statement to test for a specific prefix or whatever criteria you may have.






                                                            share|improve this answer




























                                                              0














                                                              all the solutions using awk/sed/grep seem overly complex and ugly for my situation... so i came up with this really simple solution BUT beware cus it makes some assumptions, namely the assumption that the LAST interface is the one you're interested. if you're ok with that then this is pretty clean:



                                                              ifconfig | awk '/net / { x = $2 } END { print x }'



                                                              otherwise you could do some silly if statement to test for a specific prefix or whatever criteria you may have.






                                                              share|improve this answer


























                                                                0












                                                                0








                                                                0







                                                                all the solutions using awk/sed/grep seem overly complex and ugly for my situation... so i came up with this really simple solution BUT beware cus it makes some assumptions, namely the assumption that the LAST interface is the one you're interested. if you're ok with that then this is pretty clean:



                                                                ifconfig | awk '/net / { x = $2 } END { print x }'



                                                                otherwise you could do some silly if statement to test for a specific prefix or whatever criteria you may have.






                                                                share|improve this answer













                                                                all the solutions using awk/sed/grep seem overly complex and ugly for my situation... so i came up with this really simple solution BUT beware cus it makes some assumptions, namely the assumption that the LAST interface is the one you're interested. if you're ok with that then this is pretty clean:



                                                                ifconfig | awk '/net / { x = $2 } END { print x }'



                                                                otherwise you could do some silly if statement to test for a specific prefix or whatever criteria you may have.







                                                                share|improve this answer












                                                                share|improve this answer



                                                                share|improve this answer










                                                                answered Sep 7 '17 at 16:24









                                                                mad.meeshmad.meesh

                                                                1113




                                                                1113























                                                                    0














                                                                    Simple Command to fine IP Address with default interface.



                                                                    ip route | grep src | awk '{print $NF; exit}'


                                                                    Tested on All Unix OS






                                                                    share|improve this answer




























                                                                      0














                                                                      Simple Command to fine IP Address with default interface.



                                                                      ip route | grep src | awk '{print $NF; exit}'


                                                                      Tested on All Unix OS






                                                                      share|improve this answer


























                                                                        0












                                                                        0








                                                                        0







                                                                        Simple Command to fine IP Address with default interface.



                                                                        ip route | grep src | awk '{print $NF; exit}'


                                                                        Tested on All Unix OS






                                                                        share|improve this answer













                                                                        Simple Command to fine IP Address with default interface.



                                                                        ip route | grep src | awk '{print $NF; exit}'


                                                                        Tested on All Unix OS







                                                                        share|improve this answer












                                                                        share|improve this answer



                                                                        share|improve this answer










                                                                        answered Dec 12 '18 at 20:54









                                                                        M.S.ArunM.S.Arun

                                                                        1497




                                                                        1497























                                                                            0














                                                                            You should use ip (instead of ifconfig) as it's current, maintained, and perhaps most importantly for scripting purposes, it produces a consistent & parsable output. Following are a few similar approaches:



                                                                            If you want the IPv4 address for your Ethernet interface eth0:



                                                                            $ ip -4 -o addr show eth0 | awk '{print $4}'
                                                                            192.168.1.166/24


                                                                            As a script:



                                                                            $ INTFC=eth0  
                                                                            $ MYIPV4=$(ip -4 -o addr show $INTFC | awk '{print $4}')
                                                                            $ echo $MYIPV4
                                                                            192.168.1.166/24



                                                                            The output produced above is in CIDR notation. If CIDR notation isn't wanted, it can be stripped:



                                                                            $ ip -4 -o addr show eth0 | awk '{print $4}' | cut -d "/" -f 1 
                                                                            192.168.1.166


                                                                            Another option that IMHO is "most elegant" gets the IPv4 address for whatever interface is used to connect to the specified remote host (8.8.8.8 in this case). Courtesy of @gatoatigrado in this answer:



                                                                            $ ip route get 8.8.8.8 | awk '{ print $NF; exit }'
                                                                            192.168.1.166


                                                                            As a script:



                                                                            $ RHOST=8.8.8.8  
                                                                            $ MYIP=$(ip route get $RHOST | awk '{ print $NF; exit }')
                                                                            $ echo $MYIP
                                                                            192.168.1.166


                                                                            This works perfectly well on a host with a single interface, but more advantageously will also work on hosts with multiple interfaces and/or route specifications.



                                                                            ip would be my preferred approach, but it's certainly not the only way to skin this cat. Here's another approach that uses hostname if you prefer something easier/more concise:



                                                                            $ hostname --all-ip-addresses | awk '{print $1}'  


                                                                            Or, if you want the IPv6 address:



                                                                            $ hostname --all-ip-addresses | awk '{print $2}'  





                                                                            share|improve this answer




























                                                                              0














                                                                              You should use ip (instead of ifconfig) as it's current, maintained, and perhaps most importantly for scripting purposes, it produces a consistent & parsable output. Following are a few similar approaches:



                                                                              If you want the IPv4 address for your Ethernet interface eth0:



                                                                              $ ip -4 -o addr show eth0 | awk '{print $4}'
                                                                              192.168.1.166/24


                                                                              As a script:



                                                                              $ INTFC=eth0  
                                                                              $ MYIPV4=$(ip -4 -o addr show $INTFC | awk '{print $4}')
                                                                              $ echo $MYIPV4
                                                                              192.168.1.166/24



                                                                              The output produced above is in CIDR notation. If CIDR notation isn't wanted, it can be stripped:



                                                                              $ ip -4 -o addr show eth0 | awk '{print $4}' | cut -d "/" -f 1 
                                                                              192.168.1.166


                                                                              Another option that IMHO is "most elegant" gets the IPv4 address for whatever interface is used to connect to the specified remote host (8.8.8.8 in this case). Courtesy of @gatoatigrado in this answer:



                                                                              $ ip route get 8.8.8.8 | awk '{ print $NF; exit }'
                                                                              192.168.1.166


                                                                              As a script:



                                                                              $ RHOST=8.8.8.8  
                                                                              $ MYIP=$(ip route get $RHOST | awk '{ print $NF; exit }')
                                                                              $ echo $MYIP
                                                                              192.168.1.166


                                                                              This works perfectly well on a host with a single interface, but more advantageously will also work on hosts with multiple interfaces and/or route specifications.



                                                                              ip would be my preferred approach, but it's certainly not the only way to skin this cat. Here's another approach that uses hostname if you prefer something easier/more concise:



                                                                              $ hostname --all-ip-addresses | awk '{print $1}'  


                                                                              Or, if you want the IPv6 address:



                                                                              $ hostname --all-ip-addresses | awk '{print $2}'  





                                                                              share|improve this answer


























                                                                                0












                                                                                0








                                                                                0







                                                                                You should use ip (instead of ifconfig) as it's current, maintained, and perhaps most importantly for scripting purposes, it produces a consistent & parsable output. Following are a few similar approaches:



                                                                                If you want the IPv4 address for your Ethernet interface eth0:



                                                                                $ ip -4 -o addr show eth0 | awk '{print $4}'
                                                                                192.168.1.166/24


                                                                                As a script:



                                                                                $ INTFC=eth0  
                                                                                $ MYIPV4=$(ip -4 -o addr show $INTFC | awk '{print $4}')
                                                                                $ echo $MYIPV4
                                                                                192.168.1.166/24



                                                                                The output produced above is in CIDR notation. If CIDR notation isn't wanted, it can be stripped:



                                                                                $ ip -4 -o addr show eth0 | awk '{print $4}' | cut -d "/" -f 1 
                                                                                192.168.1.166


                                                                                Another option that IMHO is "most elegant" gets the IPv4 address for whatever interface is used to connect to the specified remote host (8.8.8.8 in this case). Courtesy of @gatoatigrado in this answer:



                                                                                $ ip route get 8.8.8.8 | awk '{ print $NF; exit }'
                                                                                192.168.1.166


                                                                                As a script:



                                                                                $ RHOST=8.8.8.8  
                                                                                $ MYIP=$(ip route get $RHOST | awk '{ print $NF; exit }')
                                                                                $ echo $MYIP
                                                                                192.168.1.166


                                                                                This works perfectly well on a host with a single interface, but more advantageously will also work on hosts with multiple interfaces and/or route specifications.



                                                                                ip would be my preferred approach, but it's certainly not the only way to skin this cat. Here's another approach that uses hostname if you prefer something easier/more concise:



                                                                                $ hostname --all-ip-addresses | awk '{print $1}'  


                                                                                Or, if you want the IPv6 address:



                                                                                $ hostname --all-ip-addresses | awk '{print $2}'  





                                                                                share|improve this answer













                                                                                You should use ip (instead of ifconfig) as it's current, maintained, and perhaps most importantly for scripting purposes, it produces a consistent & parsable output. Following are a few similar approaches:



                                                                                If you want the IPv4 address for your Ethernet interface eth0:



                                                                                $ ip -4 -o addr show eth0 | awk '{print $4}'
                                                                                192.168.1.166/24


                                                                                As a script:



                                                                                $ INTFC=eth0  
                                                                                $ MYIPV4=$(ip -4 -o addr show $INTFC | awk '{print $4}')
                                                                                $ echo $MYIPV4
                                                                                192.168.1.166/24



                                                                                The output produced above is in CIDR notation. If CIDR notation isn't wanted, it can be stripped:



                                                                                $ ip -4 -o addr show eth0 | awk '{print $4}' | cut -d "/" -f 1 
                                                                                192.168.1.166


                                                                                Another option that IMHO is "most elegant" gets the IPv4 address for whatever interface is used to connect to the specified remote host (8.8.8.8 in this case). Courtesy of @gatoatigrado in this answer:



                                                                                $ ip route get 8.8.8.8 | awk '{ print $NF; exit }'
                                                                                192.168.1.166


                                                                                As a script:



                                                                                $ RHOST=8.8.8.8  
                                                                                $ MYIP=$(ip route get $RHOST | awk '{ print $NF; exit }')
                                                                                $ echo $MYIP
                                                                                192.168.1.166


                                                                                This works perfectly well on a host with a single interface, but more advantageously will also work on hosts with multiple interfaces and/or route specifications.



                                                                                ip would be my preferred approach, but it's certainly not the only way to skin this cat. Here's another approach that uses hostname if you prefer something easier/more concise:



                                                                                $ hostname --all-ip-addresses | awk '{print $1}'  


                                                                                Or, if you want the IPv6 address:



                                                                                $ hostname --all-ip-addresses | awk '{print $2}'  






                                                                                share|improve this answer












                                                                                share|improve this answer



                                                                                share|improve this answer










                                                                                answered Mar 9 at 21:06









                                                                                SeamusSeamus

                                                                                272212




                                                                                272212























                                                                                    0














                                                                                    This may not be the most robust or correct solution, but unlike most of the other solutions, the command works on both Linux and Mac (BSD).



                                                                                    host `hostname` | awk '{print $NF}'





                                                                                    share|improve this answer




























                                                                                      0














                                                                                      This may not be the most robust or correct solution, but unlike most of the other solutions, the command works on both Linux and Mac (BSD).



                                                                                      host `hostname` | awk '{print $NF}'





                                                                                      share|improve this answer


























                                                                                        0












                                                                                        0








                                                                                        0







                                                                                        This may not be the most robust or correct solution, but unlike most of the other solutions, the command works on both Linux and Mac (BSD).



                                                                                        host `hostname` | awk '{print $NF}'





                                                                                        share|improve this answer













                                                                                        This may not be the most robust or correct solution, but unlike most of the other solutions, the command works on both Linux and Mac (BSD).



                                                                                        host `hostname` | awk '{print $NF}'






                                                                                        share|improve this answer












                                                                                        share|improve this answer



                                                                                        share|improve this answer










                                                                                        answered 4 hours ago









                                                                                        wisbuckywisbucky

                                                                                        728810




                                                                                        728810























                                                                                            -2














                                                                                            hostname -I >> file_name 


                                                                                            this will do everything you want






                                                                                            share|improve this answer


























                                                                                            • hostname: invalid option -- 'l'...

                                                                                              – jasonwryan
                                                                                              Dec 23 '15 at 6:56











                                                                                            • That's a capital i. Seems to work fine although it apparently prints IP addresses of all interfaces.

                                                                                              – Joe
                                                                                              Dec 23 '15 at 7:04











                                                                                            • it is proposed in one of the previous answers. Also it does not store the IP in the variable. So what is the point of this answer?

                                                                                              – Jakuje
                                                                                              Dec 23 '15 at 8:10
















                                                                                            -2














                                                                                            hostname -I >> file_name 


                                                                                            this will do everything you want






                                                                                            share|improve this answer


























                                                                                            • hostname: invalid option -- 'l'...

                                                                                              – jasonwryan
                                                                                              Dec 23 '15 at 6:56











                                                                                            • That's a capital i. Seems to work fine although it apparently prints IP addresses of all interfaces.

                                                                                              – Joe
                                                                                              Dec 23 '15 at 7:04











                                                                                            • it is proposed in one of the previous answers. Also it does not store the IP in the variable. So what is the point of this answer?

                                                                                              – Jakuje
                                                                                              Dec 23 '15 at 8:10














                                                                                            -2












                                                                                            -2








                                                                                            -2







                                                                                            hostname -I >> file_name 


                                                                                            this will do everything you want






                                                                                            share|improve this answer















                                                                                            hostname -I >> file_name 


                                                                                            this will do everything you want







                                                                                            share|improve this answer














                                                                                            share|improve this answer



                                                                                            share|improve this answer








                                                                                            edited Dec 23 '15 at 7:26









                                                                                            muru

                                                                                            38k590166




                                                                                            38k590166










                                                                                            answered Dec 23 '15 at 6:53









                                                                                            shanushanu

                                                                                            7




                                                                                            7













                                                                                            • hostname: invalid option -- 'l'...

                                                                                              – jasonwryan
                                                                                              Dec 23 '15 at 6:56











                                                                                            • That's a capital i. Seems to work fine although it apparently prints IP addresses of all interfaces.

                                                                                              – Joe
                                                                                              Dec 23 '15 at 7:04











                                                                                            • it is proposed in one of the previous answers. Also it does not store the IP in the variable. So what is the point of this answer?

                                                                                              – Jakuje
                                                                                              Dec 23 '15 at 8:10



















                                                                                            • hostname: invalid option -- 'l'...

                                                                                              – jasonwryan
                                                                                              Dec 23 '15 at 6:56











                                                                                            • That's a capital i. Seems to work fine although it apparently prints IP addresses of all interfaces.

                                                                                              – Joe
                                                                                              Dec 23 '15 at 7:04











                                                                                            • it is proposed in one of the previous answers. Also it does not store the IP in the variable. So what is the point of this answer?

                                                                                              – Jakuje
                                                                                              Dec 23 '15 at 8:10

















                                                                                            hostname: invalid option -- 'l'...

                                                                                            – jasonwryan
                                                                                            Dec 23 '15 at 6:56





                                                                                            hostname: invalid option -- 'l'...

                                                                                            – jasonwryan
                                                                                            Dec 23 '15 at 6:56













                                                                                            That's a capital i. Seems to work fine although it apparently prints IP addresses of all interfaces.

                                                                                            – Joe
                                                                                            Dec 23 '15 at 7:04





                                                                                            That's a capital i. Seems to work fine although it apparently prints IP addresses of all interfaces.

                                                                                            – Joe
                                                                                            Dec 23 '15 at 7:04













                                                                                            it is proposed in one of the previous answers. Also it does not store the IP in the variable. So what is the point of this answer?

                                                                                            – Jakuje
                                                                                            Dec 23 '15 at 8:10





                                                                                            it is proposed in one of the previous answers. Also it does not store the IP in the variable. So what is the point of this answer?

                                                                                            – Jakuje
                                                                                            Dec 23 '15 at 8:10





                                                                                            protected by jasonwryan Dec 23 '15 at 6:59



                                                                                            Thank you for your interest in this question.
                                                                                            Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                                                                                            Would you like to answer one of these unanswered questions instead?



                                                                                            Popular posts from this blog

                                                                                            Taj Mahal Inhaltsverzeichnis Aufbau | Geschichte | 350-Jahr-Feier | Heutige Bedeutung | Siehe auch |...

                                                                                            Baia Sprie Cuprins Etimologie | Istorie | Demografie | Politică și administrație | Arii naturale...

                                                                                            Ciclooctatetraenă Vezi și | Bibliografie | Meniu de navigare637866text4148569-500570979m