通过fd链接去获取相应的本地地址和远端地址

大耗子 2021年01月20日 46次浏览

通过fd链接去获取相应的本地地址和远端地址

int get_ip_and_port_by_fd(int fd, char* local_ip, int* local_port, char* peer_ip, int* peer_port)
{
    if((!local_ip || !local_port) && (!peer_ip || !peer_port)){
        printf("ip or port mem is null\n");
        return -1;
    }
    struct sockaddr_in addr;
    char ip[20] = {0};
        socklen_t addr_len = sizeof(addr);
        int ret = -1;

    if(local_ip && local_port){
        getsockname(fd, (struct sockaddr_in *)&addr, &addr_len);
        inet_ntop(AF_INET, &(addr.sin_addr), ip, sizeof(addr));
        memcpy(local_ip, ip, strlen(ip));
        *local_port = ntohs(addr.sin_port);
        printf("local_ip:%s local_port:%d\n",local_ip, *local_port);
                ret = 0;
    }

    if(peer_ip && peer_port){
        getpeername(fd, (struct sockaddr_in *)&addr, &addr_len);
        inet_ntop(AF_INET, &(addr.sin_addr), ip, sizeof(addr));
        memcpy(peer_ip, ip, strlen(ip));
        *peer_port = ntohs(addr.sin_port);
        printf("peer_ip:%s peer_port:%d\n",peer_ip, *peer_port);
                ret = 0;
    }
    
    return ret;
}