In Linux, obtain the IP address of the specified network and the interface of netmask:
Int get_ip (char * ipaddr, char * netmask, const char * ethname)
{
Int ret =-1;
If (ipaddr & netmask & ethname)
{
Int FD, intrface;
Struct ifreq Buf [16];
Struct ifconf IFC;
If (FD = socket (af_inet, sock_dgram, 0) <0)
Return-1;
IFC. ifc_len = sizeof (BUF );
IFC. ifc_buf = (caddr_t) BUF;
If (IOCTL (FD, siocgifconf, (char *) & IFC) <0)
Goto _ error _;
Intrface = IFC. ifc_len/sizeof (struct ifreq );
While (intrface --> 0)
{
If (strstr (BUF [intrface]. ifr_name, ethname ))
{
If (IOCTL (FD, siocgifaddr, (char *) & Buf [intrface]) <0)
Goto _ error _;
Sprintf (ipaddr, "% s ",
Inet_ntoa (struct sockaddr_in *) (& Buf [intrface]. ifr_addr)-> sin_addr ));
If (IOCTL (FD, siocgifnetmask, (char *) & Buf [intrface]) <0)
Goto _ error _;
Sprintf (netmask, "% s ",
Inet_ntoa (struct sockaddr_in *) (& Buf [intrface]. ifr_netmask)-> sin_addr ));
Ret = 0;
}
}
_ Error _:
Close (FD );
}
Return ret;
}
Interface for obtaining MAC addresses:
Int get_mac (char * Mac)
{
Int FD, ret =-1;
If (MAC)
{
Struct ifreq IFR;
If (FD = socket (af_inet, sock_dgram, 0) <0)
{
Perror ("socket ");
Return-1;
}
IFR. ifr_addr.sa_family = af_inet;
Strncpy (IFR. ifr_name, "eth0", IFNAMSIZ-1 );
If (IOCTL (FD, siocgifhwaddr, & IFR) = 0)
{
Sprintf (MAC, "% 02x-% 02x-% 02x-% 02x-% 02x-% 02x ",
(Unsigned char) IFR. ifr_hwaddr.sa_data [0],
(Unsigned char) IFR. ifr_hwaddr.sa_data [1],
(Unsigned char) IFR. ifr_hwaddr.sa_data [2],
(Unsigned char) IFR. ifr_hwaddr.sa_data [3],
(Unsigned char) IFR. ifr_hwaddr.sa_data [4],
(Unsigned char) IFR. ifr_hwaddr.sa_data [5]);
Strupr (MAC );
Ret = 0;
}
Close (FD );
}
Return ret;
}