#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<errno.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<sys/socket.h>
#include<sys/ioctl.h>
#include<sys/types.h>
#include<net/if.h>
/**
+++++++++++++++++++++++++++++++
Program:- Find IP address using ioctl
+++++++++++++++++++++++++++++++
Author:- Surendra S.Patil
+++++++++++++++++++++++++++++++
I/P:- interface name ex:- “eth0 “
+++++++++++++++++++++++++++++++
O/P:- Ip address (192.168.2.2)
+++++++++++++++++++++++++++++++
*/
int main()
{
int sock_fd;
struct ifreq interface;
/* create socket and get socket descriptor */
sock_fd = socket(AF_INET,SOCK_DGRAM,0);
if (-1 == sock_fd) {
fprintf(stderr,”errno:- %d :- %s”,errno,strerror(errno));
exit(EXIT_FAILURE);
}
/* copy the interface name */
strcpy(interface.ifr_name,”eth0″);
if(-1 == ioctl(sock_fd,SIOCGIFADDR,&interface)) {
fprintf(stderr,”errno:- %d :- %s”,errno,strerror(errno));
exit(EXIT_FAILURE);
}
printf(“Interface = %s\n IP Address = %s\n”,interface.ifr_name,
inet_ntoa(((struct sockaddr_in *)&interface.ifr_addr)->sin_addr));
close(sock_fd);
exit(EXIT_SUCCESS);
}
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<errno.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<sys/socket.h>
#include<sys/ioctl.h>
#include<sys/types.h>
#include<net/if.h>
/**
+++++++++++++++++++++++++++++++
Program:- Find IP address using ioctl
+++++++++++++++++++++++++++++++
Author:- Surendra S.Patil
+++++++++++++++++++++++++++++++
I/P:- interface name ex:- “eth0 “
+++++++++++++++++++++++++++++++
O/P:- Ip address (192.168.2.2)
+++++++++++++++++++++++++++++++
*/
int main()
{
int sock_fd;
struct ifreq interface;
/* create socket and get socket descriptor */
sock_fd = socket(AF_INET,SOCK_DGRAM,0);
if (-1 == sock_fd) {
fprintf(stderr,”errno:- %d :- %s”,errno,strerror(errno));
exit(EXIT_FAILURE);
}
/* copy the interface name */
strcpy(interface.ifr_name,”eth0″);
if(-1 == ioctl(sock_fd,SIOCGIFADDR,&interface)) {
fprintf(stderr,”errno:- %d :- %s”,errno,strerror(errno));
exit(EXIT_FAILURE);
}
printf(“Interface = %s\n IP Address = %s\n”,interface.ifr_name,
inet_ntoa(((struct sockaddr_in *)&interface.ifr_addr)->sin_addr));
close(sock_fd);
exit(EXIT_SUCCESS);
}
Run the program:-
Comments