Obtain the IP address of the Local Machine (General Nic) in linux-Linux Enterprise Application-Linux server application information. For more information, see the following. Author: Star
In Unix and Linux systems, you can obtain the system IP address (gethostbyname and ioctl) in two ways)
Gethostbyname obtains the network address of the corresponding computer through domain name resolution. ioctl is a series of network functions to obtain the IP address of the local machine.
(The ioctl method is recommended. The ip address displayed in this method is the same as the ip address displayed in the ifconfig command, and can run normally on the arm board without modification. The ip address provided by gethostname () and gethostbyname () methods is inconsistent with that provided by ifconfig. You cannot [do not understand why] and cannot run properly on the arm board .)
Ioctl sample program
CODE: # include # Include # Include # Include # Include # Include # Include # Include Int main (void) { Int s; Struct ifconf conf; Struct ifreq * ifr; Char buff [BUFSIZ]; Int num; Int I; S = socket (PF_INET, SOCK_DGRAM, 0 ); Conf. ifc_len = BUFSIZ; Conf. ifc_buf = buff; Ioctl (s, SIOCGIFCONF, & conf ); Num = conf. ifc_len/sizeof (struct ifreq ); Ifr = conf. ifc_req; For (I = 0; I <num; I ++) { Struct sockaddr_in * sin = (struct sockaddr_in *) (& ifr-> ifr_addr ); Ioctl (s, SIOCGIFFLAGS, ifr ); If (ifr-> ifr_flags & IFF_LOOPBACK) = 0) & (ifr-> ifr_flags & IFF_UP )) { Printf ("% s (% s) \ n ", Ifr-> ifr_name, Inet_ntoa (sin-> sin_addr )); } Ifr ++; } } |