Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Local Ip address in c++

Tags:

c++

ip

I have a code to get local ip address. This is the code I use.

typedef std::map<string,string> settings_t;

void loadLocalIp (settings_t &ipConfig)
{
    struct ifaddrs * ifAddrStruct=NULL;
    struct ifaddrs * ifa=NULL;
    void * tmpAddrPtr=NULL;      

    getifaddrs(&ifAddrStruct);

    for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) {
        if (ifa ->ifa_addr->sa_family==AF_INET) { // check it is IP4
            // is a valid IP4 Address
            tmpAddrPtr=&((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
            char addressBuffer[INET_ADDRSTRLEN];
            inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);

            string key(ifa->ifa_name);
            string value(addressBuffer);
            cout<<key<<" =1 " <<value<<endl;
            ipConfig.insert(std::pair<string,string>(key, value));

           // printf("'%s': %s\n", ifa->ifa_name, addressBuffer); 
         }
     }
    if (ifAddrStruct!=NULL) 
        freeifaddrs(ifAddrStruct);//remember to free ifAddrStruct
}

int main()
{
    settings_t ipConfig;
    loadLocalIp(ipConfig);
    cout<<ipConfig.at("enp2s0")<<endl;
    return 0;
}

So My result, is

lo =1 127.0.0.1
enp2s0 =1 172.20.55.6
172.20.55.6

But In another computer, the interface name is different. They get result like bellow,

lo =1 127.0.0.1
ens32 =1 172.20.55.9
terminate called after throwing an instance of 'std::out_of_range'
  what():  map::at
Aborted (core dumped)

I want to get my Ip address whatever the interface name is. How can I get my local ip address if the interface name varies from different computer. It should give the ip address whatever the interface name is. How can I do this?

My question is, Now I am getting my local IP from this method. But I should get IP whatever the Interface name is. One thing, I need to find that interface name and apply it in my above code (or) Is there any other option to find that IP without that interface?

like image 517
Smith Dwayne Avatar asked Mar 17 '18 10:03

Smith Dwayne


People also ask

How do I find my localhost IP using CMD?

First, click on your Start Menu and type cmd in the search box and press enter. A black and white window will open where you will type ipconfig /all and press enter. There is a space between the command ipconfig and the switch of /all. Your ip address will be the IPv4 address.

What is IP address in C program?

The IPv4 addresses are represented in dot-decimal notation. There are four decimal numbers (all are ranging from 0 to 255). These four numbers are separated by three dots. An example of a valid IP is: 192.168.4.1.


1 Answers

I want to get my IP address whatever the interface name is.

It is difficult to reliably get the local ip address by looking at the network interface. As you have already discovered, the network interface name can be unique for each host you run on. To further complicate things, a computer may have multiple network interfaces and each of those may or may not be connected to the Internet.

You don't need to use the default interface. A more simplistic approach is to just let the OS routing table figure it out for you. You can do this by setting up a socket connection to some external server and then calling getsockname to get the local address. This example uses Google's DNS server at 8.8.8.8 to establish a socket connection but you can use whatever external server you'd like.

#include <iostream>     ///< cout
#include <cstring>      ///< memset
#include <errno.h>      ///< errno
#include <sys/socket.h> ///< socket
#include <netinet/in.h> ///< sockaddr_in
#include <arpa/inet.h>  ///< getsockname
#include <unistd.h>     ///< close

int main()
{
    const char* google_dns_server = "8.8.8.8";
    int dns_port = 53;

    struct sockaddr_in serv;
    int sock = socket(AF_INET, SOCK_DGRAM, 0);

    //Socket could not be created
    if(sock < 0)
    {
        std::cout << "Socket error" << std::endl;
    }

    memset(&serv, 0, sizeof(serv));
    serv.sin_family = AF_INET;
    serv.sin_addr.s_addr = inet_addr(google_dns_server);
    serv.sin_port = htons(dns_port);

    int err = connect(sock, (const struct sockaddr*)&serv, sizeof(serv));
    if (err < 0)
    {
        std::cout << "Error number: " << errno
            << ". Error message: " << strerror(errno) << std::endl;
    }

    struct sockaddr_in name;
    socklen_t namelen = sizeof(name);
    err = getsockname(sock, (struct sockaddr*)&name, &namelen);

    char buffer[80];
    const char* p = inet_ntop(AF_INET, &name.sin_addr, buffer, 80);
    if(p != NULL)
    {
        std::cout << "Local IP address is: " << buffer << std::endl;
    }
    else
    {
        std::cout << "Error number: " << errno
            << ". Error message: " << strerror(errno) << std::endl;
    }

    close(sock);
    return 0;
}
like image 184
Justin Randall Avatar answered Nov 01 '22 00:11

Justin Randall