erondem
Posts: 23
Joined: Wed Jul 11, 2018 12:19 pm

How to get Raspberry's IP adress with c++ Code

Fri Dec 21, 2018 12:09 pm

Hi,


My raspbery pi is doing regular tasks and send logs to the server. The network which server is running on has DHCP enabled. So sometimes IP of the raspberry can change (I thing IT guys, changes something on the network, and the IP which is assigned to raspberry is changes).
When I need to change someting on code have to search network with a scanner program and connect to the device via SSH. Till now everything is okey.

What I want to do is since raspberry can connect to the server and send some logs to db , can it detect its own IP adress once at every re-connection.And send it to the server? The program I wrote is in C++ so it has to be in C++ language.

n67
Posts: 938
Joined: Mon Oct 30, 2017 4:55 pm

Re: How to get Raspberry's IP adress with c++ Code

Fri Dec 21, 2018 12:23 pm

The usual and easy way to do this is to use system() or popen() to get the info from running one of the usual utilities (ipconfig, ip, etc). This should qualify as "doing it in C/C++".

However, people often want to do it directly in their chosen programming language. This can, of course, be done, but is more complicated. Is there any particular reason you want or need to do this (do it directly, I mean) ?
"L'enfer, c'est les autres"

G fytc hsqr rum umpbq rm qyw rm rfc kmbq md rfgq dmpsk:

Epmu Sn!

J lnacjrw njbruh-carppnanm vxm rb mnuncrwp vh yxbcb!

erondem
Posts: 23
Joined: Wed Jul 11, 2018 12:19 pm

Re: How to get Raspberry's IP adress with c++ Code

Fri Dec 21, 2018 12:54 pm

n67 wrote:
Fri Dec 21, 2018 12:23 pm
The usual and easy way to do this is to use system() or popen() to get the info from running one of the usual utilities (ipconfig, ip, etc). This should qualify as "doing it in C/C++".

However, people often want to do it directly in their chosen programming language. This can, of course, be done, but is more complicated. Is there any particular reason you want or need to do this (do it directly, I mean) ?


When the program begins it sends a log that says something "Everything is working and I am Alive" , I want that to be something like "Everything is working, I am Alive and my IP is: xx.xx.xx.xx" . That seems a proper way to me. If you have any comment on this way please dont hesitate.

I have used one system() command in my code to restart the raspberry device if certain conditions are met. I think I can use it to get IP adress

n67
Posts: 938
Joined: Mon Oct 30, 2017 4:55 pm

Re: How to get Raspberry's IP adress with c++ Code

Fri Dec 21, 2018 1:08 pm

I'm not saying there is anything wrong with the way you're doing things.

I think you want to use popen() to run, say, ifconfig, and parse what comes back.
popen() is better than system() in this case, because it gives you access to the standard output of the command (without having to do an explicit redirection to a file).

You might also be able to do it with "hostname -I" (which is what the code in /etc/rc.local uses).
"L'enfer, c'est les autres"

G fytc hsqr rum umpbq rm qyw rm rfc kmbq md rfgq dmpsk:

Epmu Sn!

J lnacjrw njbruh-carppnanm vxm rb mnuncrwp vh yxbcb!

User avatar
PeterO
Posts: 4940
Joined: Sun Jul 22, 2012 4:14 pm

Re: How to get Raspberry's IP adress with c++ Code

Fri Dec 21, 2018 1:09 pm

erondem wrote:
Fri Dec 21, 2018 12:09 pm
Hi,


My raspbery pi is doing regular tasks and send logs to the server. The network which server is running on has DHCP enabled. So sometimes IP of the raspberry can change (I thing IT guys, changes something on the network, and the IP which is assigned to raspberry is changes).
When I need to change someting on code have to search network with a scanner program and connect to the device via SSH. Till now everything is okey.

What I want to do is since raspberry can connect to the server and send some logs to db , can it detect its own IP adress once at every re-connection.And send it to the server? The program I wrote is in C++ so it has to be in C++ language.

There is example code at the bottom of the manual page for getifaddrs.

Code: Select all

GETIFADDRS(3)                 Linux Programmer's Manual                GETIFADDRS(3)

NAME
       getifaddrs, freeifaddrs - get interface addresses

SYNOPSIS
       #include <sys/types.h>
       #include <ifaddrs.h>

       int getifaddrs(struct ifaddrs **ifap);

       void freeifaddrs(struct ifaddrs *ifa);

DESCRIPTION
       The  getifaddrs() function creates a linked list of structures describing the
       network interfaces of the local system,
This will give you exactly the information you want using the programming language you are already using without using some kludge of running a utility via "system" which you would then have to parse the output from.

Use the correct tools for the job.

For your convenience here is the code from the manual page....

Code: Select all

#define _GNU_SOURCE     /* To get defns of NI_MAXSERV and NI_MAXHOST */
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netdb.h>
#include <ifaddrs.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <linux/if_link.h>

int main(int argc, char *argv[])
{
    struct ifaddrs *ifaddr, *ifa;
    int family, s, n;
    char host[NI_MAXHOST];

    if (getifaddrs(&ifaddr) == -1) {
	perror("getifaddrs");
	exit(EXIT_FAILURE);
    }



/* Walk through linked list, maintaining head pointer so we
   can free list later */

    for (ifa = ifaddr, n = 0; ifa != NULL; ifa = ifa->ifa_next, n++) {
	if (ifa->ifa_addr == NULL)
	    continue;

	family = ifa->ifa_addr->sa_family;

	/* Display interface name and family (including symbolic
	   form of the latter for the common families) */

	printf("%-8s %s (%d)\n",
	       ifa->ifa_name,
	       (family == AF_PACKET) ? "AF_PACKET" :
	       (family == AF_INET) ? "AF_INET" :
	       (family == AF_INET6) ? "AF_INET6" : "???",
	       family);

	/* For an AF_INET* interface address, display the address */

	if (family == AF_INET || family == AF_INET6) {
	    s = getnameinfo(ifa->ifa_addr,
			    (family == AF_INET) ? sizeof(struct sockaddr_in) :
			    sizeof(struct sockaddr_in6),
			    host, NI_MAXHOST,
			    NULL, 0, NI_NUMERICHOST);
	    if (s != 0) {
		printf("getnameinfo() failed: %s\n", gai_strerror(s));
		exit(EXIT_FAILURE);
	    }

	    printf("\t\taddress: <%s>\n", host);

	} else if (family == AF_PACKET && ifa->ifa_data != NULL) {
	    struct rtnl_link_stats *stats = ifa->ifa_data;

	    printf("\t\ttx_packets = %10u; rx_packets = %10u\n"
		   "\t\ttx_bytes   = %10u; rx_bytes   = %10u\n",
		   stats->tx_packets, stats->rx_packets,
		   stats->tx_bytes, stats->rx_bytes);
	}
    }

    freeifaddrs(ifaddr);
    exit(EXIT_SUCCESS);
}
That should get you on the right path :-)
PeterO
Discoverer of the PI2 XENON DEATH FLASH!
Interests: C,Python,PIC,Electronics,Ham Radio (G0DZB),1960s British Computers.
"The primary requirement (as we've always seen in your examples) is that the code is readable. " Dougie Lawson

danjperron
Posts: 3390
Joined: Thu Dec 27, 2012 4:05 am
Location: Québec, Canada

Re: How to get Raspberry's IP adress with c++ Code

Fri Dec 21, 2018 1:28 pm

Ok another link to get all IP addresses IPv4 and IPV6

It is in c so it is portable to c++.

https://domen.ipavec.net/en/get-ip-ipv6 ... s-linux-c/

it works well

Code: Select all

pi@pibplus:~ $ ./getip
Interface lo
Mac address: 00:00:00:00:00:00
MTU: 65536
Ip address: 127.0.0.1
Broadcast: 0.0.0.0
Netmask: 255.0.0.0
IPv6 address: ::1, prefix: 128, scope: Host

Interface eth0
Mac address: b8:27:eb:65:12:7f
MTU: 1500

Interface wlan0
Mac address: 7c:dd:90:68:e8:c3
MTU: 1500
Ip address: 10.11.12.121
Broadcast: 10.11.12.255
Netmask: 255.255.255.0
IPv6 address: fe80::d7e4:b141:2c9b:d3f9, prefix: 64, scope: Link

erondem
Posts: 23
Joined: Wed Jul 11, 2018 12:19 pm

Re: How to get Raspberry's IP adress with c++ Code

Fri Dec 21, 2018 4:57 pm

PeterO wrote:
Fri Dec 21, 2018 1:09 pm
erondem wrote:
Fri Dec 21, 2018 12:09 pm
Hi,


My raspbery pi is doing regular tasks and send logs to the server. The network which server is running on has DHCP enabled. So sometimes IP of the raspberry can change (I thing IT guys, changes something on the network, and the IP which is assigned to raspberry is changes).
When I need to change someting on code have to search network with a scanner program and connect to the device via SSH. Till now everything is okey.

What I want to do is since raspberry can connect to the server and send some logs to db , can it detect its own IP adress once at every re-connection.And send it to the server? The program I wrote is in C++ so it has to be in C++ language.

There is example code at the bottom of the manual page for getifaddrs.

Code: Select all

GETIFADDRS(3)                 Linux Programmer's Manual                GETIFADDRS(3)

NAME
       getifaddrs, freeifaddrs - get interface addresses

SYNOPSIS
       #include <sys/types.h>
       #include <ifaddrs.h>

       int getifaddrs(struct ifaddrs **ifap);

       void freeifaddrs(struct ifaddrs *ifa);

DESCRIPTION
       The  getifaddrs() function creates a linked list of structures describing the
       network interfaces of the local system,
This will give you exactly the information you want using the programming language you are already using without using some kludge of running a utility via "system" which you would then have to parse the output from.

Use the correct tools for the job.

For your convenience here is the code from the manual page....

Code: Select all

#define _GNU_SOURCE     /* To get defns of NI_MAXSERV and NI_MAXHOST */
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netdb.h>
#include <ifaddrs.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <linux/if_link.h>

int main(int argc, char *argv[])
{
    struct ifaddrs *ifaddr, *ifa;
    int family, s, n;
    char host[NI_MAXHOST];

    if (getifaddrs(&ifaddr) == -1) {
	perror("getifaddrs");
	exit(EXIT_FAILURE);
    }



/* Walk through linked list, maintaining head pointer so we
   can free list later */

    for (ifa = ifaddr, n = 0; ifa != NULL; ifa = ifa->ifa_next, n++) {
	if (ifa->ifa_addr == NULL)
	    continue;

	family = ifa->ifa_addr->sa_family;

	/* Display interface name and family (including symbolic
	   form of the latter for the common families) */

	printf("%-8s %s (%d)\n",
	       ifa->ifa_name,
	       (family == AF_PACKET) ? "AF_PACKET" :
	       (family == AF_INET) ? "AF_INET" :
	       (family == AF_INET6) ? "AF_INET6" : "???",
	       family);

	/* For an AF_INET* interface address, display the address */

	if (family == AF_INET || family == AF_INET6) {
	    s = getnameinfo(ifa->ifa_addr,
			    (family == AF_INET) ? sizeof(struct sockaddr_in) :
			    sizeof(struct sockaddr_in6),
			    host, NI_MAXHOST,
			    NULL, 0, NI_NUMERICHOST);
	    if (s != 0) {
		printf("getnameinfo() failed: %s\n", gai_strerror(s));
		exit(EXIT_FAILURE);
	    }

	    printf("\t\taddress: <%s>\n", host);

	} else if (family == AF_PACKET && ifa->ifa_data != NULL) {
	    struct rtnl_link_stats *stats = ifa->ifa_data;

	    printf("\t\ttx_packets = %10u; rx_packets = %10u\n"
		   "\t\ttx_bytes   = %10u; rx_bytes   = %10u\n",
		   stats->tx_packets, stats->rx_packets,
		   stats->tx_bytes, stats->rx_bytes);
	}
    }

    freeifaddrs(ifaddr);
    exit(EXIT_SUCCESS);
}
That should get you on the right path :-)
PeterO


It is a programming question but I could not assign IP to a variable. How should I do that?

Code: Select all

if (family == AF_INET || family == AF_INET6) {
                   s = getnameinfo(ifa->ifa_addr,
                           (family == AF_INET) ? sizeof(struct sockaddr_in) :
                                                 sizeof(struct sockaddr_in6),
                           host, NI_MAXHOST,
                           NULL, 0, NI_NUMERICHOST);
                   if (s != 0) {
                       printf("getnameinfo() failed: %s\n", gai_strerror(s));
                       //exit(EXIT_FAILURE);
                   }
                   
		   if(ifa->ifa_name == "eth0")
		   {
		   printf("Found \n");
		    }
			else{
			printf("Not Found \n");
			}
		

               } 


It always print Not Found

User avatar
PeterO
Posts: 4940
Joined: Sun Jul 22, 2012 4:14 pm

Re: How to get Raspberry's IP adress with c++ Code

Fri Dec 21, 2018 5:49 pm

erondem wrote:
Fri Dec 21, 2018 4:57 pm
It always print Not Found
Ok, so you posted in the "advanced users" forum, and asked about C++ (claiming to have already written your code in C++) , but it would appear you don't have much C or C++ experience ? Is that right ?

If you are a new C/C++ programmer please say so and we can move forward from there....

PeterO
Discoverer of the PI2 XENON DEATH FLASH!
Interests: C,Python,PIC,Electronics,Ham Radio (G0DZB),1960s British Computers.
"The primary requirement (as we've always seen in your examples) is that the code is readable. " Dougie Lawson

Return to “Advanced users”