关于perror的使用

delphiwcdj 2011-03-03 05:18:12
关于perro有这样一句解释:
perror should be called right after the error was produced, otherwise it can be overwritten in calls to other functions.
下面有错误发生但是却输出no error,不知道是什么原因,请大大门解释下,谢谢!
情景:

#include <stdio.h>
#include <WinSock.h>
#define PORT 8516
#pragma comment(lib, "ws2_32.lib")

int main()
{
// 将此后注释掉,socket()会返回失败,但是perror并没有输出错误
/*
//initialize Winsock
WORD wVersion=MAKEWORD(2,0);
WSADATA wsData;
int nResult=0;
nResult=WSAStartup(wVersion,&wsData);
*/

SOCKET sockfd,newfd,numbytes;
int sin_size=sizeof(struct sockaddr_in);
char rev[100000];
sockaddr_in server,client;
server.sin_addr.s_addr=inet_addr("127.0.0.1");
server.sin_family=AF_INET;
server.sin_port=htons(PORT);
memset(server.sin_zero,'0',8);

if((sockfd=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP)) == -1)
{
perror("socket");// 输出 no error, 并没有输出错误,是什么原因?
}
int nRe=0;
if((nRe=bind(sockfd,(sockaddr *)&server,sizeof(struct sockaddr)))==-1) perror("bind");

if(listen(sockfd,10)==-1) perror("listen");
printf("正在监听端口%d中....\n",PORT);
while(1)
{
if((newfd=accept(sockfd,(sockaddr *)&client,&sin_size))==-1)
continue;
printf("已经与IP为%s的客户建立连接........\n",inet_ntoa(client.sin_addr));
if(numbytes=recv(newfd,rev,100000,0)==-1) perror("recv error");
printf("正在接受数据....\n");
rev[numbytes]='\0';
printf("数据已成功接收:\n%s",rev);
shutdown(newfd,2);
}
return 0;
}
...全文
246 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
arong1234 2011-03-06
  • 打赏
  • 举报
回复
我想你该揭帖了,大家能回答的都告诉你了,顶了,你还希望得到啥?[Quote=引用 5 楼 delphiwcdj 的回复:]
顶下 。
[/Quote]
arong1234 2011-03-03
  • 打赏
  • 举报
回复
perror只能处理设置到errno上的错误码,不是每个库都这么设置错误码的
这似乎是 C Runtime的函数吧
delphiwcdj 2011-03-03
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 jixingzhong 的回复:]

试试 GetLastError 吧。
[/Quote]
是的,一般是这样用的,偶尔看到别人用perror,自己试了下发现有些不对
printf("Error at socket():%ld\n",WSAGetLastError());
jixingzhong 2011-03-03
  • 打赏
  • 举报
回复
试试 GetLastError 吧。
justkk 2011-03-03
  • 打赏
  • 举报
回复
windows平台通常用WSAGetLastError()

64,439

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

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