Reprinted: c ++ access to the local IP address

windows are two ways to obtain the IP address of the next;

A way to obtain IPv4 and IPv6, but required WSAStartup;

That can only get to IPv4, but need not WSAStartup;

as follows:

Method one :( can get IPv4 and IPv6)

#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <Winsock2.h>
#include <stdio.h>
#include <iostream>
#include <cstring>
#include<ws2tcpip.h>
#pragma comment(lib, "ws2_32.lib ")  //linking to the library
using namespace std;
int get_ip()
{
    struct addrinfo *ailist, *aip;
    struct addrinfo hint;
    struct sockaddr_in6 *sinp6;
    PHOSTENT hostinfo;
    char hostname [ 255 ] = { 0 }; // hostname    
    char * Port = " 3294 " ;       // port number 
    const  char * addr;
     int ILRC;
    the gethostname (hostname, the sizeof (hostname));
     IF ((= Hostinfo the gethostbyname (hostname)) == NULL) // obtain a local address ipv4 
    {
        errno = GetLastError();
        fprintf(stderr,"gethostbyname Error:%d\n", errno);
        return 1;
    }
    LPCSTR ip;
    the while (* (hostinfo-> the h_addr_list)! = NULL) // output ipv4 address 
    {
        ip = inet_ntoa(*(struct in_addr *) *hostinfo->h_addr_list);
        printf("ipv4 addr = %s\n\n", ip);
        hostinfo->h_addr_list++;
    }
    hint.ai_family = the AF_INET6;         // defining hint provided 
    hint.ai_socktype = SOCK_STREAM;    // here, but such setting socket type SOCK_DGRAM 
    hint.ai_flags = AI_PASSIVE into;        // number of flags flag. Commonly used AI_CANONNAME; 
    hint.ai_protocol = 0 ;              // set the protocol is generally 0, the default 
    hint.ai_addrlen = 0 ;               // below can not be set as 0, or a NULL 
    hint.ai_canonname = NULL;
    hint.ai_addr = NULL;
    hint.ai_next = NULL;
    ILRC = the getaddrinfo (hostname, Port, & hint, & ailist); // get the address information of the host name 
    IF (ILRC < 0 )
    {
        char str_error[100];
        strcpy(str_error, (char *)gai_strerror(errno));
        printf("str_error = %s", str_error);
        return 0;
    }
    if(ailist == NULL)
    {
        printf("sorry not find the IP address,please try again \n");
    }
    for (AIP = ailist;! = NULL AIP; AIP = aip-> ai_next) // display the information acquired 
    {
        AIP -> ai_family == AF_INET6;
        sinp6 = ( struct sockaddr_in6 *) aip-> ai_addr;     // Why is the for loop, first looking down 
        int I;
        printf("ipv6 addr = ");
        for(i = 0; i < 16; i++)
        {
            if(((i-1)%2) && (i>0))
            {
                printf(":");
            }
            printf("%02x",sinp6->sin6_addr.u.Byte[i]);
        }
        printf(" \n");
        printf(" \n");
    }
    while(1);
}
int main () {

    WORD wVersionRequested;
    WSAData wsaData;
    int err;
    wVersionRequested = MAKEWORD ( . 1 , . 1 );
    err = WSAStartup( wVersionRequested, &wsaData );//initiate the ws2_32.dll and match the version
    if ( err != 0 )
    {
        return 0;
    }
    if ( LOBYTE( wsaData.wVersion ) != 1 ||   //if the version is not matched ,then quit and terminate the ws3_32.dll 
        HIBYTE( wsaData.wVersion ) != 1 )
    {
        WSACleanup( );
        return 0;
    }
    get_ip();
    WSACleanup( );
    return 0;
}

Method Two :( only take into IPv4)

 

//#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <WinSock2.h>
#include <Iphlpapi.h>
#include <iostream>
using namespace std;
#pragma comment (lib, "Iphlpapi.lib") // required libraries to add Iphlpapi.lib
//#pragma comment(lib, "ws2_32.lib")

int main(int argc, char* argv[])
{
    // PIP_ADAPTER_INFO structure pointer card information stored in native
    PIP_ADAPTER_INFO pIpAdapterInfo = new IP_ADAPTER_INFO();
    // size of the structure is obtained, parameters for GetAdaptersInfo
    unsigned long stSize = sizeof(IP_ADAPTER_INFO);
    // call the function GetAdaptersInfo filled pIpAdapterInfo pointer variable; stSize wherein the parameter is both an input of an output
    int nRel = GetAdaptersInfo(pIpAdapterInfo, &stSize);
    // record the number of NICs
    DWORD netCardNum = 0;
    GetNumberOfInterfaces(&netCardNum);
    cout << "number of NICs:" << netCardNum << endl; netCardNum = 0;
    // record number of IP addresses on each card
    int IPnumPerNetCard = 0;
    if (ERROR_BUFFER_OVERFLOW == nRel)
    {
        // If the function returns ERROR_BUFFER_OVERFLOW
        // then the parameters passed GetAdaptersInfo memory space is insufficient, while its spread stSize, indicates the size of the required
        // This is also why stSize both an input output is a
        // release the original memory space
        delete pIpAdapterInfo;
        // reapply memory space to store all card information
        pIpAdapterInfo = (PIP_ADAPTER_INFO)new BYTE[stSize];
        // call the function again GetAdaptersInfo, filling pIpAdapterInfo pointer variable
        nRel = GetAdaptersInfo (pIpAdapterInfo, & stSize);
    }
    if (ERROR_SUCCESS == nRel)
    {
        // output card information
        // may have more cards, and hence to judge by cycle
        while (pIpAdapterInfo)
        {
            cout << "网卡序号:" << ++netCardNum <<"\t"<<pIpAdapterInfo->Index << endl;
            cout << "网卡名称:" << pIpAdapterInfo->AdapterName << endl;
            cout << "Card Description:" << pIpAdapterInfo-> Description << endl;
            cout << "card type:";
            switch (pIpAdapterInfo->Type)
            {
            case MIB_IF_TYPE_OTHER:        cout << "OTHER" << endl; break;
            case MIB_IF_TYPE_ETHERNET:    cout << "ETHERNET" << endl; break;
            case MIB_IF_TYPE_TOKENRING:    cout << "TOKENRING" << endl; break;
            case MIB_IF_TYPE_FDDI:        cout << "FDDI" << endl; break;
            case MIB_IF_TYPE_PPP:        cout << "PPP" << endl; break;
            case MIB_IF_TYPE_LOOPBACK:    cout << "LOOPBACK" << endl; break;
            case MIB_IF_TYPE_SLIP:        cout << "SLIP" << endl; break;
            default:                    cout << "" << endl; break;
            }
            cout << "MAC address:";
            for (DWORD i = 0; i < pIpAdapterInfo->AddressLength; i++)
                if (i < pIpAdapterInfo->AddressLength - 1)
                {
                    printf("%02X-", pIpAdapterInfo->Address[i]);
                }
                else
                {
                    printf("%02X\n", pIpAdapterInfo->Address[i]);
                }
            cout << "NIC IP address as follows:" << endl;
            IPnumPerNetCard = 0;
            // How could NIC IP, and therefore through the loop to judge
            IP_ADDR_STRING *pIpAddrString = &(pIpAdapterInfo->IpAddressList);
            do
            {
                cout << "IP number on the card:" << ++ IPnumPerNetCard << endl;
                cout << "IP 地址:" << pIpAddrString->IpAddress.String << endl;
                cout << "Subnet Mask:" << pIpAddrString-> IpMask.String << endl;
                cout << "网关地址:" << pIpAdapterInfo->GatewayList.IpAddress.String << endl;
                pIpAddrString = pIpAddrString->Next;
            } while (pIpAddrString);
            pIpAdapterInfo = pIpAdapterInfo-> Next;
            cout << "--------------------------------------------------------------------" << endl;
        }

    }
    // free up memory space
    if (pIpAdapterInfo)
    {
        delete pIpAdapterInfo;
    }
    return 0;
}

 

Under Linux, see: http://www.cnblogs.com/lzpong/p/6956439.html

 

Guess you like

Origin www.cnblogs.com/freedomworld/p/11703456.html