分类:
2008-11-12 13:51:34
使用getsockname来获取一个socket的local和remote的ip, 端口, address family等信息
的操作。
wxString CSocket::GetLocalIP() const
{
struct sockaddr_storage addr;
socklen_t addr_len = sizeof(addr);
int res = getsockname(m_fd, (sockaddr*)&addr, &addr_len);
if (res)
return _T("");
return AddressToString((sockaddr *)&addr, addr_len, false);
}
wxString CSocket::GetPeerIP() const
{
struct sockaddr_storage addr;
socklen_t addr_len = sizeof(addr);
int res = getpeername(m_fd, (sockaddr*)&addr, &addr_len);
if (res)
return _T("");
return AddressToString((sockaddr *)&addr, addr_len, false);
}
int CSocket::GetAddressFamily() const
{
struct sockaddr_storage addr;
socklen_t addr_len = sizeof(addr);
int res = getsockname(m_fd, (sockaddr*)&addr, &addr_len);
if (res)
return AF_UNSPEC;
return ((sockaddr*)&addr)->sa_family;
}
int CSocket::GetLocalPort(int& error)
{
struct sockaddr_storage addr;
socklen_t addr_len = sizeof(addr);
error = getsockname(m_fd, (sockaddr*)&addr, &addr_len);
if (error)
{
#ifdef __WXMSW__
error = ConvertMSWErrorCode(error);
#endif
return -1;
}
if (addr.ss_family == AF_INET)
{
struct sockaddr_in* addr_v4 = (sockaddr_in*)&addr;
return ntohs(addr_v4->sin_port);
}
else if (addr.ss_family == AF_INET6)
{
struct sockaddr_in6* addr_v6 = (sockaddr_in6*)&addr;
return ntohs(addr_v6->sin6_port);
}
error = EINVAL;
return -1;
}
int CSocket::GetRemotePort(int& error)
{
struct sockaddr_storage addr;
socklen_t addr_len = sizeof(addr);
error = getpeername(m_fd, (sockaddr*)&addr, &addr_len);
if (error)
{
#ifdef __WXMSW__
error = ConvertMSWErrorCode(error);
#endif
return -1;
}
if (addr.ss_family == AF_INET)
{
struct sockaddr_in* addr_v4 = (sockaddr_in*)&addr;
return ntohs(addr_v4->sin_port);
}
else if (addr.ss_family == AF_INET6)
{
struct sockaddr_in6* addr_v6 = (sockaddr_in6*)&addr;
return ntohs(addr_v6->sin6_port);
}
error = EINVAL;
return -1;
}