Linux obtains the IP address MAC address netmask address

Source: Internet
Author: User

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;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.