Obtain IP addresses from multiple NICs (VC)

Source: Internet
Author: User

Method: The wsaioctl function of the method for obtaining NICs in C Language
In WinSock, you can call the wsaioctl () function and obtain network interface information by setting the flag to sio_get_interface_list. The function is defined in msdn as follows:

Int wsaioctl (
Socket S, // socket handle
DWORD dwiocontrolcode, // control code. In msdn, sio_get_interface_list is not converted through macro-defined computation.
Lpvoid lpvinbuffer, // address of the input buffer
DWORD cbinbuffer, // size of the inbound/outbound Buffer
Lpvoid lpvoutbuffer, // output buffer address
DWORD cboutbuffer, // size of the output buffer
Lpdword lpcbbytesreturned, // actual number of output bytes
Lpwsaoverlapped lpoverlapped, // address of the wsaoverlapped Structure
Lpwsaoverlapped_completion_routine lpcompletionroutine // call history pointer after the operation ends
);


This function is defined in ws2tcpip. H. Therefore, the header file must be included first. In addition, the storage information structure should be mentioned as follows:

Typedef struct _ interface_info
{
U_long iiflags; // interface type and status
Struct sockaddr iiaddress; // interface IP Address
Struct sockaddr iibroadcastaddress; // broadcast address corresponding to the interface
Struct sockaddr iinetmask; // subnet mask corresponding to the interface
} Interface_info;

The core code is as follows:

//
// Return the socket information structure. The parameter type: TYPE =-1 indicates that all Nic information is listed. If the parameter is not-1, the system displays the information of the specified Nic.
//

Int getioinfo (INT type)
{
Int ret;
Int nface; // ioinfo count
Int I;
Socket infosock;
// Number of bytes for saving the actual Nic Interface Information
DWORD bytesreturned;
Infosock = wsasocket (af_inet, sock_dgram, 0, 0, 0 );
If (invalid_socket = infosock)
{
Printf ("wsasocket error: % s \ n", wsagetlasterror ());
Return 0;
}
// Sets the flag sio_get_interface_list to obtain network interface information.
Ret = wsaioctl (infosock, sio_get_interface_list, & ioinfo, sizeof (ioinfo), & bytesreturned );
If (socket_error = RET)
{
Printf ("wsaioctl error: % s \ n", wsagetlasterror ());
Return 0;
}
// Calculate the number of NIC Interfaces
Nface = bytesreturned/sizeof (interface_info );

// Type =-1 -- list all adapter Infomation
// Type! =-1 -- list the number [type] adapter Information
Switch (type)
{
Case-1:
{
For (I = 0; I <nface; I ++) // cyclically outputs all Network Interface Information
{
Printf ("\ nthe % d netinterface information: \ n", I );
// Obtain the NIC address and convert the IP format to the string format.
Printf ("IP Address: % s \ n", inet_ntoa (ioinfo [I]. iiaddress. addressin. sin_addr ));
}
Return 1;
Break;
}
Default:
{
If (type <nface & type> = 0 ){
Printf ("\ nthe % d netinterface information: \ n", type );
// Obtain the NIC address and convert the IP format to the string format.
Printf ("IP Address: % s \ n", inet_ntoa (ioinfo [type]. iiaddress. addressin. sin_addr ));
} Else {
Printf ("the net inteface % d is not found! \ N ", type );
Return 0;
}
Return 1;
Break;
}
}
Return 1;
}

Method: getadaptersinfo function for obtaining NICs in C Language
Next, in the previous article, we implemented it through the second method. The information obtained by this method is more complete and practical. The main function is getadaptersinfo, which is provided in the header file iphlpapi. h. However, the file is not installed in the environment where vc6.0 is installed by default. It is included in the Platform SDK (software development kit, I extracted the contained file headers and related files from the installed SDK package and put them in the Development Directory. The download will be provided at the end of the article.
First, understand the getadaptersinfo function:

DWORD getadaptersinfo (
// The buffer for receiving data, pointing to a structure ip_adapter_info
Pip_adapter_info padapterinfo,
// Pointer to the size of the output buffer
Pulong poutbuflen
);

The most important parameter in this function is the first parameter. What is the structure? The description in msdn is as follows:

Typedef struct _ ip_adapter_info {
Struct _ ip_adapter_info * Next; // linked list pointer, pointing to the next unit
DWORD comboindex;
Char adaptername [max_adapter_name_length + 4]; // physical name of the Interface Information
Char description [max_adapter_description_length + 4]; // Interface Description
Uint addresslength; // The length of the MAC address
Byte Address [max_adapter_address_length]; // MAC address
DWORD index;
Uint type;
Uint dhcpenabled;
Pip_addr_string currentipaddress;
Ip_addr_string ipaddresslist; // ip address list
Ip_addr_string gatewaylist; // gateway address list
Ip_addr_string dhcpserver; // DHCP address
Bool havewins;
Ip_addr_string primarywinsserver; // the WINS server is preferred.
Ip_addr_string secondarywinsserver; // backup WINS Server
Time_t leaseobtained;
Time_t leaseexpires;
} Ip_adapter_info, * pip_adapter_info;

I only introduced several common parameters above. These parameters are sufficient. The following is a small example of implementation. The Code is as follows:

# Include "stdafx. H"
# Include "Winsock. H"
# Include "stdio. H"
# Include "iphlpapi/iphlpapi. H" // getadaptersinfo ()
# Pragma comment (Lib, "iphlpapi/iphlpapi. lib ")

Int main (INT argc, char * argv [])
{
// Network Interface Information, up to 20
Ip_adapter_info ioinfo [20];
// Initialize the linked list structure pointer
Pip_adapter_info pioinfo = NULL;
DWORD result = 0;
// Obtain the size
Unsigned long nlen = sizeof (ioinfo );
// Obtain the NIC Information
Result = getadaptersinfo (ioinfo, & nlen );
If (no_error! = Result)
{
Printf ("getadaptersinfo error. \ n ");
Return 0;
} Else {
Pioinfo = ioinfo; // point the linked list pointer to the Network Interface Information Storage Structure
While (pioinfo! = NULL) // read the NIC cyclically if it is not null
{
Static int num;
Num ++;
Printf ("\ n ┌ ── num. % d ── ─ ── accept \ n", num );
Printf ("│ name: % s \ n", pioinfo-> adaptername );
Printf ("│ Desc: % s \ n", pioinfo-> description );
Printf ("│ IP: % s \ n", pioinfo-> ipaddresslist. IPaddress. String );
Printf ("│ Mac: % 02x: % 02x: % 02x: % 02x: % 02x: % 02x \ n", pioinfo-> Address [0], pioinfo-> Address [2], pioinfo-> Address [3], pioinfo-> Address [4], pioinfo-> Address [5]);
Printf ("│ Gateway: % s \ n", pioinfo-> gatewaylist. IPaddress. String );
Printf ("└ ── ─ num. % d ── ─ accept \ n", num );
// The linked list Pointer Points to the next one.
Pioinfo = pioinfo-> next;
}
}
Return 0;
}

Method 3: hostent structure Traversal

# Include "stdio. H"
# Include "winsock2.h"
# Pragma comment (Lib, "ws2_32.lib ")

Int main (INT argc, char * argv [])
{
Word wversionrequested;
Wsadata;
Int err;

Wversionrequested = makeword (2, 2 );

Err = wsastartup (wversionrequested, & wsadata );
If (Err! = 0 ){
Return 0;
}
If (lobyte (wsadata. wversion )! = 2 |
Hibyte (wsadata. wversion )! = 2 ){
Wsacleanup ();
}

Char host [255];
Memset (host, 0,255 );
Gethostname (host, 255 );
Printf ("% s \ n", host );


Struct hostent * Host;
Host = gethostbyname (host );
Struct in_addr ADDR;
For (INT I = 0; I ++ ){
If (host-> h_addr_list [I]! = '\ 0 '){
Memmove (& ADDR, host-> h_addr_list [I], 4 );
Char * IP;
IP = inet_ntoa (ADDR );
Printf ("IP: % s \ n", ip );
} Else {
Break;
}
}
Wsacleanup ();

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.