C + + get local IP address

Source: Internet
Author: User
Tags htons

C IP Address knowledge points:
 structsockaddr {unsigned Shortsa_family; Charsa_data[ -];  }; sockaddr_in Detailed sa_family is the address family, is generally "af_xxx" form. Most commonly used are af_inet, which represents the address group Sa_data is a 14-byte protocol address. SOCKADDR is a generic socket address, specific to the Internet socket, with the following structure, both of which can be type conversionstructsockaddr_in { Short   intsin_family;//address family generally af_inet (family of addresses) pf_inet (protocol family)Unsigned Short   intSin_port;//Sin_port Storage port number (using network byte order), under Linux, the range of the port number is 0~65535, and the port number of the 0~1024 range is already used or reserved by the system                structIN_ADDR sin_addr;//Storage IP AddressUnsignedCharsin_zero[8];//Sin_zero is an empty byte reserved to keep sockaddr and sockaddr_in two data structures the same size        }; structIn_addr is a 32-bit IP address. structin_addr {union {struct{U_char s_b1,s_b2,s_b3,s_b4;}                        S_un_b; struct{u_short s_w1,s_w2;}                        S_un_w; U_long s_addr; //s_addr storing IP addresses in network byte order} S_un; #defineS_addr S_un. S_addr        }; 

In a C + +when you write a network program, you often encounter problems with the network order and host order of the bytes. It is possible to use the 4 functions of htons (), Ntohl (), Ntohs (), htons (). Conversion function between network byte order and local byte order:#include <arpa/inet.h>htonl ()--"Host to Network Long"Ntohl ()--"Network to Host Long"htons ()--"Host to Network short"Ntohs ()--"Network to Host short"These functions are required because computer data represents two byte orders: Nbo and HBO network byte Order Nbo (network byte order): stored in order from high to low, using uniform network byte order on the network avoids compatibility issues. Host byte sequence (hbo,host byte order): Different machine HBO is not the same, related to CPU design, the order of data is determined by the CPU, and operating system independent. such as the Intel x86 structure, the short type number 0x1234 is expressed as A, the int number 0x12345678 is represented as 78 About  the  Asuch as the IBM Power PC structure, the short type number 0x1234 is expressed as the, the int number 0x12345678 is represented as 12 the  About  +For This reason there is no communication between machines of different architectures, so converting to a contract sequence, that is, the network byte order, is actually the same order as the Power PC.
In PC development, there are ntohl and HTONL functions that can be used to convert network bytes and host bytes.
This data structure is like this:structhostent {Char*H_name; Char**h_aliases; intH_addrtype; inth_length; Char**h_addr_list;    }; #defineH_ADDR H_addr_list[0]here is the detailed information about this data structure:structthe official name of the hostent:h_name– address. h_aliases– Empty bytes-A pointer to the prestaged name of the address. h_addrtype– address type;    Usually a af_inet.   The bit length of the h_length– address. h_addr_list– 0 Bytes-Host network address pointer.   Network byte order. H_addr-the first address in the h_addr_list. GetHostByName () Returns a pointer to the struct hostent, or an empty (NULL) pointer when successful. (However, unlike before, the Errno,h_errno setting error message is not set.) Take a look at the following Herror (). ) but how to use it?This function is not as difficult to use as it seems. Here is an example: #include<stdio.h>#include<stdlib.h>#include<errno.h>#include<netdb.h>#include<sys/types.h>#include<netinet/inch.h>intMainintargcChar*argv[]) {structHostent *h;if(ARGC! =2) {/*Check the command line*/fprintf (stderr,"Usage:getip address\n"); Exit (1); } if((H=gethostbyname (argv[1]) = = NULL) {/*Get address information*/Herror ("gethostbyname"); Exit (1); } printf ("Host Name:%s\n", h->h_name); printf ("IP Address:%s\n", Inet_ntoa (* (structIN_ADDR *) h->( h_addr))); return 0; You should not use Perror () to print the error message (because errno is not used) when using gethostbyname (), and you should call Herror (). Pretty simple, you just pass a string that holds the machine name (for example,"whitehouse.gov") to GetHostByName (), and then from the data structure returned

structGet information in hostent. The only thing that may be confusing is the output of IP address information. H->h_addr is aChar*,
But what Inet_ntoa () needs isstructIn_addr. So I converted H->h_addr into astructIN_ADDR *, then get the data.


============================================================
Reference Address: http://blog.csdn.net/liuqinstudy/article/details/8813932
#include<stdio.h>#include<sys/ioctl.h>#include<sys/socket.h>#include<unistd.h>#include<sys/types.h>#include<netdb.h>#include<net/if.h>#include<arpa/inet.h>#include<iostream>using namespacestd;intGET_LOCAL_IP (unsignedLong&IP) { intSFD, intr; structIfreq buf[ -]; structifconf IFC; SFD= Socket (Af_inet, SOCK_DGRAM,0); if(SFD <0) return-1; Ifc.ifc_len=sizeof(BUF); Ifc.ifc_buf=(caddr_t) buf; if(The IOCTL (SFD, siocgifconf,Char*) &IFC)) return-1; Intr= Ifc.ifc_len/sizeof(structifreq); while(intr-->0&& ioctl (SFD, SIOCGIFADDR, (Char*) &buf[intr])); Close (SFD); IP= Ntohl ((structsockaddr_in*) (&AMP;BUF[INTR].IFR_ADDR))sin_addr.s_addr); return 0;}intMain () {unsignedLongIP =0; intRET =get_local_ip (IP); if(ret = =0) {cout<< IP <<Endl; } Else{cout<<"Err"<<Endl; } return 0;}

C + + get local IP address

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.