Getting IPV4 address from a sockaddr structure

后端 未结 6 1742
一整个雨季
一整个雨季 2020-12-07 22:32

How can I extract an IP address into a string? I can\'t find a reference that tells me how char sa_data[14] is encoded.

6条回答
  •  时光取名叫无心
    2020-12-07 23:01

    You can use getnameinfo for Windows and for Linux.

    Assuming you have a good (i.e. it's members have appropriate values) sockaddr* called pSockaddr:

    char clienthost[NI_MAXHOST];  //The clienthost will hold the IP address.
    char clientservice[NI_MAXSERV];
    int theErrorCode = getnameinfo(pSockaddr, sizeof(*pSockaddr), clienthost, sizeof(clienthost), clientservice, sizeof(clientservice), NI_NUMERICHOST|NI_NUMERICSERV);
    
    if( theErrorCode != 0 )
    {
        //There was an error.
        cout << gai_strerror(e1) << endl;
    }else{
        //Print the info.
        cout << "The ip address is = " << clienthost << endl;
        cout << "The clientservice = " << clientservice << endl;
    }
    

提交回复
热议问题