How to obtain IP address and MAC Adr in Linux

Source: Internet
Author: User


Methods for obtaining IP and MAC Adr in Linux: struct ifreq {char ifr_name [IFNAMSIZ]; union {struct sockaddr ifru_addr; struct sockaddr Dr; short ifru_flags; int ifru_metric; caddr_t ifru_data;} ifr_ifru;}; www.2cto.com # include <net/if. h> # include <net/if_arp.h> # include <arpa/inet. h> # include <errno. h> # define ETH_NAME "eth0" int main () {int sock; struct sockaddr_in sin; struct ifreq ifr; unsigned char arp [6]; www.2cto.com sock = socket (AF_INET, SOCK_DGRAM, 0); if (sock =-1) {perror ("socket"); return-1;} strncpy (ifr. ifr_name, ETH_NAME, IFNAMSIZ); ifr. ifr_name [IFNAMSIZ-1] = 0; if (ioctl (sock, SIOCGIFADDR, & ifr) = 0) // obtain ip {memcpy (& sin, & ifr. ifr_addr, sizeof (sin); fprintf (stdout, "eth0: % s \ n", inet_ntoa (sin. sin_addr);} www.2cto.com if (ioctl (sock, SIOCGIFHWADDR, & ifr) = 0) // obtain mac {memcpy (arp, ifr. ifr_hwaddr.sa_data, 6); printf ("adapter hardware address x: x \ n", arp [0], arp [1], arp [2], arp [3], arp [4], arp [5]);} return 0 ;}
 

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.