errno 的用法
时间:2010-04-28 来源:mars51
|
errno这个变量在/usr/include/errno.h中定义。格式为 #ifndef errno
extern int errno;
#endif
故要在程序当中使用errno,要先#include <errno.h> 这个头文件 下面是我写的一段小程序 #include <stdio.h>
#include <string.h>
#include <errno.h>
#include <arpa/inet.h>
#include <sys/socket.h> int main(int argv,char *argc[])
{
int iSocket = 0;
struct sockaddr_in stServer;
stServer.sin_family = AF_INET;
stServer.sin_port = htons(6666);
stServer.sin_addr.s_addr = inet_addr("127.0.0.1");
memset(&stServer.sin_zero,0,8);
if (-1 == (iSocket = socket(AF_INET,SOCK_STREAM,0)))
{
perror("socket");
return -1;
}
if (-1 == connect(iSocket,(struct sockaddr *)&stServer,sizeof(struct sockaddr)))
{
printf("errno is %d\n",errno);
if (errno == ECONNREFUSED)
printf("ECONNREFUSED!\n");
}
return 0;
} 编译:gcc errno.c 程序运行结果: [root@localhost errno]# ./a.out
errno is 111
ECONNREFUSED!
[root@localhost errno]# 相信大家唯一可能有点不明白的就是ECONNREFUSED这个东西怎么来的。没关系,因为我以前也不明白~~。 ECONNREFUSED的来历需要通过看man 2 connect来获得了。 在打开的文本中注意看下面这一行: RETURN VALUE
If the connection or binding succeeds, zero is returned. On error, -1 is returned, and errno is set appropriately. ERRORS
The following are general socket errors only. There may be other domain- specific error codes. EACCES For Unix domain sockets, which are identified by pathname: Write permission is denied on the socket...
RETURN VALUE是对connect返回值的说明。成功返回0。不成功返回-1,而且errno被赋值为相应的值。在我这里就是ECONNREFUSED啦。 ERRORS就是解释有可能被赋值到errno中的每个选项的意思。如ECONNREFUSED的解释是: ECONNREFUSED
No one listening on the remote address. 另外ECONNREFUSED 为111, 是在/usr/include/asm-generic/errno.h中定义的,如下: #define ETIMEDOUT 110 /* Connection timed out */
#define ECONNREFUSED 111 /* Connection refused */
#define EHOSTDOWN 112 /* Host is down */ 但不同的系统貌似不同,我现在用的是FC8.示例程序代码在附件中
相关阅读 更多 +