Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

The method of obtaining Native MAC/IP address by linux

Shulou Source: shulou.com Published: 2022-06-03 07:20:46 09月29日 Update

Function: query local IP/MAC address and filter out 127.0.0.1 loop-back address

Applicable: linux, ubuntu 16.04 debugging passed

# include

# include

# include

# include

# include

# include

# include

# include

# include

# include

# include

# include

# include

# include

# include

Void getLocalMacIp ()

{

Int i

Int sock_mac

Char hname [128]

Struct hostent * hent

Struct in_addr * paddr = 0

Struct ifaddrs * ifAddrStruct=NULL

Struct ifreq ifr_mac

Void * tmpAddrPtr=NULL

Struct ifreq buf [16]

Struct ifconf ifc

Int interface_num

Char nif_name [128] = {0}

Char addressBuffer [128]

Unsigned char macaddr [6] = {0}

Unsigned char * pFirstByte

/ /-

/ / get device IP address, discard loopback

/ /-

Gethostname (hname, sizeof (hname))

Hent = gethostbyname (hname)

Printf ("[% s] [% d] host:% s\ n", _ _ FILE__, _ LINE__, hent- > h_name)

Getifaddrs & ifAddrStruct)

While (ifAddrStructneighbor null)

{

If (ifAddrStruct- > ifa_addr- > sa_family==AF_INET)

{

TmpAddrPtr = & ((struct sockaddr_in *) ifAddrStruct- > ifa_addr)-> sin_addr

PFirstByte = (unsigned char*) tmpAddrPtr

If (* pFirstByte! = 127)

{

Paddr = tmpAddrPtr

Inet_ntop (AF_INET, tmpAddrPtr, addressBuffer, 128)

Printf ("[% s] [% d] NIF% s address% s\ n", _ _ FILE__, _ _ LINE__

IfAddrStruct- > ifa_name, addressBuffer)

/ /-

/ / remember NIF name for future use

/ /-

Strcpy (nif_name, ifAddrStruct- > ifa_name)

}

}

IfAddrStruct=ifAddrStruct- > ifa_next

}

/ /-

/ / get device MAC address, discard loopback

/ /-

Sock_mac = socket (AF_INET, SOCK_DGRAM, 0)

If (sock_mac > 0)

{

Ifc.ifc_len = sizeof (buf)

Ifc.ifc_req = buf

Ioctl (sock_mac, SIOCGIFCONF, (char *) & ifc)

Interface_num = ifc.ifc_len / sizeof (struct ifreq)

While (interface_num--)

{

If (nif_name [0] & & strcmp (nif_name, BUF [interface _ num] .ifr _ name))

{

Continue

}

Ioctl (sock_mac, SIOCGIFHWADDR, (char *) & BUF [interface _ num])

Memcpy (macaddr, & buf [interface _ num] .ifr _ hwaddr.sa_data [0], 6)

/ / printf ("NIF% s", buf [interface _ num] .ifr _ name)

/ / printf ("mac x:x:x:x:x:x\ n"

/ / macaddr [0], macaddr [1], macaddr [2], macaddr [3], macaddr [4], macaddr [5])

}

Close (sock_mac)

}

}

Tags: Address local machine function query method Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia MySQL vpn Apple OPPO Reno