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

  • Post author:
  • Post category:其他


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

“`c

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;

}

“`



版权声明:本文为G_Super_Mouse原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。