Reproduced in: http://blog.csdn.net/k346k346/article/details/48231933
The native IP address is often used when programming Linux networks. This article lists common ways to prepare for a rainy moment.
Getting the native IP address is a fairly flexible operation because the settings for the network address are very flexible and allow the user to personalize the settings. For example, a computer can have more than one physical network card or virtual network card, a network card can be bound to multiple IP addresses, users can set the network card alias, you can rename the network card. The network topology of the user's computer is unknown, the hostname setting is an option, and the same can be used to bind multiple host names to a computer, and this information will be affected. Disconnected from the network, a separate network address does not make any sense. When you encounter a scenario in which you must obtain a computer IP, you should consider placing this option in a configuration file, which is set by the user himself.
Refer to the network and books, programming to obtain a native IP address about the following methods.
method One: IOCTL () get local IP address The IOCTL () function and struct struct ifreq and struct struct ifconf can be used under Linux to obtain various information about the network interface.
The process is to get all the local interface information through Ictol, stored in the ifconf structure, and then take out each ifreq represents the IP information (usually each NIC corresponds to an IP address, such as: "Eth0 ..., eth1 ...").
First understand struct struct ifreq and struct struct ifconf:
Ifconf is usually used to store all interface information.If.hstruct IFCONF {int Ifc_len;/* Size of buffer */union {Char *ifcu_buf;/*input from user->kernel*/struct Ifreq *ifcu_req;/* return from kernel->user*/} IFC_IFCU;};#Define IFC_BUF ifc_ifcu.ifcu_buf/*buffer Address * *#define ifc_req ifc_ifcu.ifcu_req/*array of Structures*/// Ifreq information used to hold an interface //if.hstruct ifreq { char Ifr_name[ifnamsiz]; Union {struct sockaddr ifru_addr; Span class= "Hljs-keyword" >struct sockaddr ifru_dstaddr; struct sockaddr ifru_broadaddr; short ifru_flags; int ifru_metric; caddr_t ifru_data;} Ifr_ifru;}; #define ifr_addr ifr_ifru.ifru_addr#define ifr_dstaddr ifr_ifru.ifru_dstaddr #define ifr_broadaddr ifr_ifru.ifru_broadaddr
If the IP address of the machine is bound to the first network card, specify the network card name, without obtaining all the information of the network card, can be obtained, see the following function:
string getLocalIP(){ int inet_sock; struct ifreq ifr; char ip[32]={NULL}; inet_sock = socket(AF_INET, SOCK_DGRAM, 0); strcpy(ifr.ifr_name, "eth0"); ioctl(inet_sock, SIOCGIFADDR, &ifr); strcpy(ip, inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr)); return string(ip);}
If you want to get all the network interface information, see the following code:
#include <netdb.h>#include <arpa/inet.h>#include <sys/socket.h>#include <unistd.h>#include <sys/ioctl.h>#include <net/if.h>#include <stdio.h>#include <stdlib.h>int main (int argc,char* argv[]) {int sockfd;struct ifconf ifconf;struct Ifreq *ifreq;Char buf[512];BufferInitialize ifconf Ifconf.ifc_len =512; Ifconf.ifc_buf = BUF;if (sockfd =socket (Af_inet,sock_dgram,0)) <0) {perror ("Socket");Exit1); } IOCTL (SOCKFD, siocgifconf, &ifconf);Get all interface informationThe next one gets the IP address ifreq = (struct ifreq*) ifconf.ifc_buf;printf"ifconf.ifc_len:%d\n", Ifconf.ifc_len);printfsizeof ( struct ifreq)); for (int i= (Ifconf.ifc_len/ sizeof (struct ifreq)); I>0; i--) {if (ifreq->ifr_flags = AF_INET) {//for IPv4 printf (" name =[%s]\n ", ifreq-> Ifr_name); printf ( "local addr = [%s]\n", Inet_ntoa (((struct sockaddr_in*) & (IFREQ->IFR_ADDR)) (->SIN_ADDR)); ifreq++; }} getchar (); //system ("pause");//not used in Linux return 0;}
Run output:
method Two: GetSockName () Gets the local IP address If a TCP connection is established, the local and peer IP and port numbers can be obtained through the getsockname and Getpeername functions. The premise is that a connection has been established with the other party. The reference code is as follows:
#include <sys/socket.h>#include <arpa/inet.h>#include <unistd.h>#include <netdb.h>int main (int argc,char* argv[]) {int Fd=socket (Af_inet,sock_stream,0);To create a local sock descriptorstruct sockaddr_in servaddr,localaddr,peeraddr; Socklen_t Len;Initialize the server address and connect bzero (&SERVADDR,sizeof (SERVADDR)); Servaddr.sin_family=af_inet; Servaddr.sin_port=htons (port);Port itself specifieschar* servip= "177.56.23.4 ";Server-side IP inet_pton (af_inet,servip,&servaddr.sin_addr);if (Connect (FD, (struct sockaddr*) &servaddr,sizeof (SERVADDR)) <0) {cerr<<"Connect Error" <<endl;Return-1; }Char buf[30]=""; Bzero (&LOCALADDR,sizeof (LOCALADDR)); GetSockName (FD, (struct sockaddr*) &localaddr,&len) //get local information cout<< "local IP is" <<inet_ntop (af_inet,& Localaddr.sin_addr,buf,sizeof (BUF)) << "Local port is" <<ntohs (Localaddr.sin_port) <<endl; Bzero (&peeraddr,sizeof (PEERADDR)); Getpeername (FD, ( struct sockaddr*) &peeraddr,&len); //get peer info cout<< "Peer IP is "<< inet_ntop (Af_inet,&peeraddr.sin_addr,buf,sizeof (BUF)) << "peer port is" <<ntohs (peeraddr.sin_port) <<endl; return 1;}
The following two methods, all through the host name to obtain the host's IP address, when obtaining the local IP address, is generally a loopback address, but can be effectively based on the host name to obtain the host IP address of the network, such as the domain name to obtain the corresponding IP address.
To obtain the exact IP address of a NIC binding, obtain it according to the IOCTL () and interface name (e.g. eth0), as specified above.
Method Three: getaddrinfo () Get the local IP address Note that getaddrinfo () can complete the host name and service name-to-address mappings in the network host, but generally cannot be used to obtain a local IP address, and when it is used to obtain a local IP address, Typically, the 127.0.0.1 local loopback address is returned. Required header file:
#include <sys/types.h>#include <sys/socket.h>#include <netdb.h>
The use cases are as follows:
#include <netdb.h>#include <arpa/inet.h>#include <sys/socket.h>#include <unistd.h>#include <stdio.h>#include <stdlib.h>int main (int argc,char* argv[]) {Char host_name[128]={null}; GetHostName (HOST_NAME,sizeof (HOST_NAME));Get the local host nameprintf"Host_name:%s\n", host_name);struct Addrinfo *ailist=null,*aip=null;struct sockaddr_in *saddr;Char *addr;int Ret=getaddrinfo (host_name,null,null,&ailist);for (aip=ailist; aip!=null; aip=aip->ai_next) {if (aip->ai_family==af_inet) {saddr= (struct sockaddr_in* ) aip->ai_addr; Addr=inet_ntoa (SADDR->SIN_ADDR); } printf ( "addr:%s\n", addr);} printf ( "\ n-----------------Baidu Host Info-------------------\ n "); Getaddrinfo ( "www.baidu.com", "http", null,&ailist); for (aip=ailist; aip!=null; aip=aip->ai_next) {if (aip->ai_ family==af_inet) {saddr= (struct sockaddr_in*) aip->ai_addr; Addr=inet_ntoa (saddr- >SIN_ADDR); } printf ( "Baidu addr:%s\n", addr);} getchar (); return 0;}
Compiling this program with GCC will cause errors of error:dereferencing pointer to incomplete type, using g++ compile pass, program output:
method Four: GetHostName () gets the function of the local IP address gethostname () and getaddrinfo (), which is typically used to obtain the IP address of the host through a hostname or service name, such as a domain name. However, to obtain a local IP address, the loopback address 127.0.0.1 is generally obtained.
string Getlocalip (char* local_ip) {//when acquiring a local IP, it is generally 127.0.0.1 char host_name[128]=struct hostent *host_ent; GetHostName (host_name, sizeof (host _name)); Host_ent = gethostbyname (HOST_NAME); const char* first_ip = Inet_ntoa (* ( struct in_addr*) (Host_ent->h_addr_list[0])); memcpy (Local_ip, first_ip, 16); return string (HOST_NAME);}
Note that the address of the host is a list, because when a host has multiple network interfaces, and multiple NICs or a network card is bound to multiple IP addresses, there will naturally be multiple IP addresses. The above code obtains the first IP address based on the host name.
References [1]http://blog.sina.com.cn/s/blog_9df3961501010hzj.html [2]http://blog.csdn.net/darennet/article/details/9338819
Common ways to get local IP addresses programmed under Linux