获取客户端ip地址

int GetPeerIP(int peer_fd, std::string& ipv4_or_ipv6_addr){
    int client_fd = peer_fd;
    
    // discovery client information
    sockaddr_in addr;
    socklen_t addrlen = SmtSizeof(addr);
    if(getpeername(client_fd, (sockaddr*)&addr, &addrlen) == -1){
        SmtWarn("discovery client information failed, fd=%d, errno=%d(%#x)", client_fd, errno, errno);
        return OSErrorCode::ServerSocketGetIPError;
    }

    // ip v4 or v6
    char buf[INET6_ADDRSTRLEN];
    SmtMemset(buf, 0, SmtSizeof(buf));
    
    if((inet_ntop(addr.sin_family, &addr.sin_addr, buf, SmtSizeof(buf))) == NULL){
        SmtWarn("convert client information failed, fd=%d, errno=%d(%#x)", client_fd, errno, errno);
        return OSErrorCode::ServerSocketGetIPError;
    }
    SmtTrace("incoming a client ip=%s, fd=%d", buf, client_fd);
    
    ipv4_or_ipv6_addr = buf;
    
    return ErrorCode::Success;
}

你可能感兴趣的:(获取客户端ip地址)