GetPeerName返回异常IP和Port

羽飞 2012-06-27 04:01:57
先贴代码:

int32 GetPeerName(int sock, char* ip, int len, unsigned short &port)
{
int32 iRet = -1;
char szLog[1024];
char szErrorBuf[128];
memset(ip, 0, sizeof(ip));
port = 0;
if (sock <= 0 )
{
REALTIME_LOG("%s:%s:%d, GetPeerName Error ! SockFd = %d", __FILE__,__func__,__LINE__,sock);
return -1;
}

//1-获取到struct sockaddr;
struct sockaddr peeraddr;
#ifdef HPUX
int nAddrLen = sizeof(peeraddr);
#else
socklen_t nAddrLen;
#endif
//getpeername返回0表示成功,其他失败
if ( ::getpeername(sock, &peeraddr, &nAddrLen) != 0 )
{
int32 iErrNo = errno;
strerror_r( iErrNo, szErrorBuf, sizeof(szErrorBuf) );

REALTIME_LOG("%s:%s:%d, getpeername Error ! errno=%d, errorcode=%s \n", __FILE__,__func__,__LINE__,iErrNo,szErrorBuf);
return -1;
}
//2-获取ip
if (NULL == ::inet_ntop(AF_INET, &( (struct sockaddr_in *)&peeraddr)->sin_addr, ip, len) )
{
int32 iErrNo = errno;
strerror_r( errno, szErrorBuf, sizeof(szErrorBuf) );

REALTIME_LOG("%s:%s:%d, inet_ntop Error ! errno=%d, errorcode=%s \n",__FILE__,__func__,__LINE__, iErrNo,szErrorBuf);
return -1;
}
//3-获取port
port = ntohs((*(struct sockaddr_in *)&peeraddr).sin_port);
return 0;
}



这个进程accept到一个socket描述字,用它去发送数据,send返回成功,但是用上面的GetPeerName得到的Ip和Port是0.0.0.0和0
曾经在HP-UX和SunOS都返回正常过,出现异常的这台机器是 SunOS bilttdc-1 5.10 Generic_147440-12 sun4v sparc sun4v

请大侠们帮忙看下,小弟感激不尽
...全文
337 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
羽飞 2012-07-08
  • 打赏
  • 举报
回复
这个可能跟平台相关的
Linux上面出问题了,HP和SunOS上、AIX都正常
羽飞 2012-07-07
  • 打赏
  • 举报
回复
版主是谁?把我的帖子删掉有意思吗?
赵4老师 2012-07-06
  • 打赏
  • 举报
回复
inet_ntoa
The Windows Sockets inet_ntoa function converts an (Ipv4) Internet network address into a string in Internet standard dotted format.

char FAR * inet_ntoa (
struct in_addr in
);

Parameters
in
[in] A structure that represents an Internet host address.
Remarks
The inet_ntoa function takes an Internet address structure specified by the in parameter and returns an ASCII string representing the address in ".'' (dot) notation as in "a.b.c.d''. The string returned by inet_ntoa resides in memory that is allocated by Windows Sockets. The application should not make any assumptions about the way in which the memory is allocated. The data is guaranteed to be valid until the next Windows Sockets function call within the same thread, but no longer. Therefore, the data should be copied before another Windows Sockets call is made.
Return Values
If no error occurs, inet_ntoa returns a char pointer to a static buffer containing the text address in standard ".'' notation. Otherwise, it returns NULL.

W170532934 2012-07-06
  • 打赏
  • 举报
回复
路过,不知道是什么问题呢。 socklen_t nAddrLen;--》 socklen_t nAddrLen = sizeof(peeraddr);初始化下试试。
羽飞 2012-07-06
  • 打赏
  • 举报
回复
大侠们讲解一下这个getpeername的namelen参数
羽飞 2012-07-06
  • 打赏
  • 举报
回复
getpeername的namelen参数未初始化,这个会有问题吗?

3,881

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 其它技术问题
社区管理员
  • 其它技术问题社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧