How to get the IP Address of a LINUX machine programmatically

If you have a cool piece of software to share, but you are not hosting it officially yet, please dump it in here. If you have code snippets that are useful, please donate!
Post Reply
dode
Earned a small fee
Earned a small fee
Posts: 23
Joined: Sun Mar 06, 2016 10:22 am

How to get the IP Address of a LINUX machine programmatically

Post by dode »

Code: Select all

#include <wx/wfstream.h>
#include <wx/txtstrm.h>
#include <wx/tokenzr.h>

// Lambda get IP Address
auto getIPAddress = [&]()
{
    // Locate first device ...
    uint iLineCount = 0;
    wxString deviceName = wxEmptyString;
    wxFileInputStream input(wxT("/proc/net/route"));
    wxTextInputStream text(input, wxT("\x09"), wxConvUTF8);
    while(input.IsOk() && !input.Eof())
    {
        wxString line = text.ReadLine();
        if(iLineCount++)
        {
            wxStringTokenizer tokenizer(line, wxDEFAULT_DELIMITERS);
            while(tokenizer.HasMoreTokens())
            {
                deviceName = tokenizer.GetNextToken();
                break;
            }
        }

        if(!deviceName.IsEmpty())
            break;
    }

    // Run ifconfig on device
    wxString ipAddress = wxEmptyString;
    wxArrayString output, errors;
    wxExecute(wxT("ifconfig ") + deviceName, output, errors);
    if(!output.IsEmpty() && errors.isEmpty())
    {
        wxString ipLine = output.Item(1);
        ipAddress = ipLine.SubString(ipLine.Find(wxT(":")) + 1, ipLine.Find(wxT("Bcast:")) - 2);
    }
    return ipAddress;
};
DavidHart
Site Admin
Site Admin
Posts: 4252
Joined: Thu Jan 12, 2006 6:23 pm
Location: IoW, UK

Re: How to get the IP Address of a LINUX machine programmatically

Post by DavidHart »

Hi,

I tested this. First, in the line:
if(!output.IsEmpty() && errors.isEmpty())
the isEmpty needs an initial I, not i.

It then failed to give an output. I'm using debian as non-root, so /sbin/ isn't in my $PATH. It worked if I hard-coded /sbin/ifconfig.

However that gave the expected result: 192:168:0:2, which is the local IP address of this machine. Was that your intention? I suspect most people reading the topic title will have been expecting to see the IP address supplied by their ISP. AFAIK it's not possible to obtain that without looking outside the box.

Regards,

David
dode
Earned a small fee
Earned a small fee
Posts: 23
Joined: Sun Mar 06, 2016 10:22 am

Re: How to get the IP Address of a LINUX machine programmatically

Post by dode »

Yes that was the general Idea.
I used that with lUbuntu, and opensuse and the result was ok ...

Regards
Dode
DavidHart
Site Admin
Site Admin
Posts: 4252
Joined: Thu Jan 12, 2006 6:23 pm
Location: IoW, UK

Re: How to get the IP Address of a LINUX machine programmatically

Post by DavidHart »

Yes that was the general Idea.
Which? To get the local address? If so, I suggest you alter the topic's title to say that.
I used that with lUbuntu, and opensuse and the result was ok ...
It is for me with ubuntu too, but in openSUSE 42.1 typing 'ifconfig' in a terminal gives:
Absolute path to ifconfig is /sbin/ifconfig, so running it may require superuser privileges (eg. root).
Typing /sbin/ifconfig worked OK though.

Perhaps your code should check if /sbin/ is in the $PATH and, If not, use the filepath rather than the filename. Or, better, always use /sbin/ifconfig if it exists.
dode
Earned a small fee
Earned a small fee
Posts: 23
Joined: Sun Mar 06, 2016 10:22 am

Re: How to get the IP Address of a LINUX machine programmatically

Post by dode »

Ok,

Here is the corrected Version

Code: Select all

// Lambda get IP Address
auto getIPAddress = [&]()
{
    // Locate first device ...
    uint iLineCount = 0;
    wxString deviceName = wxEmptyString;
    wxFileInputStream input(wxT("/proc/net/route"));
    wxTextInputStream text(input, wxT("\x09"), wxConvUTF8);
    while(input.IsOk() && !input.Eof())
    {
        wxString line = text.ReadLine();
        if(iLineCount++)
        {
            wxStringTokenizer tokenizer(line, wxDEFAULT_DELIMITERS);
            while(tokenizer.HasMoreTokens())
            {
                deviceName = tokenizer.GetNextToken();
                break;
            }
        }

        if(!deviceName.IsEmpty())
            break;
    }

    // Run ifconfig on device
    wxString ipAddress = wxEmptyString;
    wxArrayString output, errors;
    if(!deviceName.IsEmpty())
        wxExecute(wxT("/sbin/ifconfig ") + deviceName, output, errors);
    if(!output.IsEmpty() && errors.IsEmpty())
    {
        wxString ipLine = output.Item(1);
        ipAddress = ipLine.SubString(ipLine.Find(wxT(":")) + 1, ipLine.Find(wxT("Bcast:")) - 2);
    }
    return ipAddress;
};
dode
Earned a small fee
Earned a small fee
Posts: 23
Joined: Sun Mar 06, 2016 10:22 am

Re: How to get the IP Address of a LINUX machine programmatically

Post by dode »

Under lUbuntu

env | grep sbin

shows PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
(default installation no manual additon to the PATH ...)

Regards,
Dode
iwbnwif
Super wx Problem Solver
Super wx Problem Solver
Posts: 282
Joined: Tue Mar 19, 2013 8:52 pm

Re: How to get the IP Address of a LINUX machine programmatically

Post by iwbnwif »

Out of interest, did you try the suggestions on this page:

https://wiki.wxwidgets.org/Getting_IP_Address_Of_Host

I just did and they both work on Ubuntu 14.04. The link on the bottom of the Wiki page points to code that appears to do exactly what you want?

Maybe its also worth looking at getifaddrs?
wxWidgets 3.1.2, MinGW64 8.1.0, g++ 8.1.0, Ubuntu 19.04, Windows 10, CodeLite + wxCrafter
Some people, when confronted with a GUI problem, think "I know, I'll use Eclipse RCP". Now they have two problems.
dode
Earned a small fee
Earned a small fee
Posts: 23
Joined: Sun Mar 06, 2016 10:22 am

Re: How to get the IP Address of a LINUX machine programmatically

Post by dode »

Following:

Code: Select all

wxIPV4address addr;
addr.Hostname(wxGetFullHostName());
wxString ipAddr = addr.IPAddress();
Under lUbuntu 16.04 returns "0.0.0.0"

as for the :

Code: Select all

 wxIPV4address remote;
 remote.Hostname(_T("www.wxwidgets.org"));
 remote.Service(80);
 
 wxIPV4address local;
 
 wxSocketClient client;
 if(client.Connect(remote)) client.GetLocal(local);
 
 wxString ipAddr=local.IPAddress();
might be ok (although never tried ) but i need that to work also in a closed environment where only LAN exists ...

Regards
Dode.
Post Reply