C++根据SOCKET获取套接字IP、Port等信息

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

//通过套接字获取IP、Port等地址信息
bool GetAddressBySocket(SOCKET m_socket,SOCKADDR_IN &m_address)
{
    memset(&m_address, 0, sizeof(m_address));
    int nAddrLen = sizeof(m_address);
  
    //根据套接字获取地址信息
    if(::getpeername(m_socket, (SOCKADDR*)&m_address, &nAddrLen) != 0)
    {
        printf("Get IP address by socket failed!n");
        return false;
    }
      
    //读取IP和Port
    cout<<"IP: "<<::inet_ntoa(m_address.sin_addr)<<"  PORT: "<<ntohs(m_address.sin_port)<<endl;
    return true;
}