Obtaining the IP address of a Linux system is a common task in networking applications. It can be helpful when troubleshooting network issues, configuring network, managing network security, etc. This tutorial demonstrates how to get the IP address on Linux using C++.
The ioctl
function can be used to perform various operations on a socket, including obtaining an IP address for a specified network interface on Linux.
In the following code, we first create a socket using the socket
function. We then create an ifreq
structure and populate its ifr_name
field with the name of the desired network interface (in this case, wlo1
). We then call the ioctl
function to obtain the IP address for the interface. Using the inet_ntoa
function, we convert the binary IP address to a human-readable string. Note that we create a character array with a size of INET_ADDRSTRLEN
. It defines the maximum length of an IPv4 address string in dotted decimal notation, including the terminating null byte. Finally, we print IP address to the console.
#include <sys/ioctl.h>
#include <linux/if.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>
#include <iostream>
int main()
{
int fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
struct ifreq ifr{};
strcpy(ifr.ifr_name, "wlo1");
ioctl(fd, SIOCGIFADDR, &ifr);
close(fd);
char ip[INET_ADDRSTRLEN];
strcpy(ip, inet_ntoa(((sockaddr_in *) &ifr.ifr_addr)->sin_addr));
std::cout << ip << std::endl;
return 0;
}
Here's an example of what the output of this code might look like:
192.168.0.195
Leave a Comment
Cancel reply