socket 错误码

来源:互联网 发布:node.js 显示所有版本 编辑:程序博客网 时间:2024/04/27 21:44

最近在网络编程使用的过程中,发现errno会经常使用。因此决定在此做个留用,以备以后使用。。。

 虽然errno是非线程安全的,但是可以通过几种机制保证其安全。。

 最近在使用的过程中获得了errno,程序无法执行,也不知道如何解决问题。因此,理解每一个返回的errno整数值的含义是很重要的。。

这个我们可以通过strerror函数来实现。。

strerror(返回整数errno对应的错误原因的描述字符串)

所需头文件:  #include
函数声明:    char * strerror(int errnum);

输入:          整数errno

输出:         返回描述错误原因的字符串指针
功能:         用来依参数errnum 的错误代码来查询其错误原因的描述字符串,然后将该字符串指针返回。
示例:
#include 
#include

#define NUM    150
int main(void)
{
    int i;    
    for ( i=0; i<num; i++)
    {
        printf( "%d:%s\n", i, strerror(i) );
    }       
    return 0;
}

运行结果:

0:Success
1:Operation not permitted
2:No such file or directory
3:No such process
4:Interrupted system call
5:Input/output error
6:No such device or address
7:Argument list too long
8:Exec format error
9:Bad file descriptor
10:No child processes
11:Resource temporarily unavailable
12:Cannot allocate memory
13:Permission denied
14:Bad address
15:Block device required
16:Device or resource busy
17:File exists
18:Invalid cross-device link
19:No such device
20:Not a directory
21:Is a directory
22:Invalid argument
23:Too many open files in system
24:Too many open files
25:Inappropriate ioctl for device
26:Text file busy
27:File too large
28:No space left on device
29:Illegal seek
30:Read-only file system
31:Too many links
32:Broken pipe
33:Numerical argument out of domain
34:Numerical result out of range
35:Resource deadlock avoided
36:File name too long
37:No locks available
38:Function not implemented
39:Directory not empty
40:Too many levels of symbolic links
41:Unknown error 41
42:No message of desired type
43:Identifier removed
44:Channel number out of range
45:Level 2 not synchronized
46:Level 3 halted
47:Level 3 reset
48:Link number out of range
49:Protocol driver not attached
50:No CSI structure available
51:Level 2 halted
52:Invalid exchange
53:Invalid request descriptor
54:Exchange full
55:No anode
56:Invalid request code
57:Invalid slot
58:Unknown error 58
59:Bad font file format
60:Device not a stream
61:No data available
62:Timer expired
63:Out of streams resources
64:Machine is not on the network
65:Package not installed
66:Object is remote
67:Link has been severed
68:Advertise error
69:Srmount error
70:Communication error on send
71:Protocol error
72:Multihop attempted
73:RFS specific error
74:Bad message
75:Value too large for defined data type
76:Name not unique on network
77:File descriptor in bad state
78:Remote address changed
79:Can not access a needed shared library
80:Accessing a corrupted shared library
81:.lib section in a.out corrupted
82:Attempting to link in too many shared libraries
83:Cannot exec a shared library directly
84:Invalid or incomplete multibyte or wide character
85:Interrupted system call should be restarted
86:Streams pipe error
87:Too many users
88:Socket operation on non-socket
89:Destination address required
90:Message too long
91:Protocol wrong type for socket
92:Protocol not available
93:Protocol not supported
94:Socket type not supported
95:Operation not supported
96:Protocol family not supported
97:Address family not supported by protocol
98:Address already in use
99:Cannot assign requested address
100:Network is down
101:Network is unreachable
102:Network dropped connection on reset
103:Software caused connection abort
104:Connection reset by peer
105:No buffer space available
106:Transport endpoint is already connected
107:Transport endpoint is not connected
108:Cannot send after transport endpoint shutdown
109:Too many references: cannot splice
110:Connection timed out
111:Connection refused
112:Host is down
113:No route to host
114:Operation already in progress
115:Operation now in progress
116:Stale NFS file handle
117:Structure needs cleaning
118:Not a XENIX named type file
119:No XENIX semaphores available
120:Is a named type file
121:Remote I/O error
122:Disk quota exceeded
123:No medium found
124:Wrong medium type
125:Operation canceled
126:Required key not available
127:Key has expired
128:Key has been revoked
129:Key was rejected by service
130:Owner died
131:State not recoverable
132:Unknown error 132
133:Unknown error 133
134:Unknown error 134
135:Unknown error 135
136:Unknown error 136
137:Unknown error 137
138:Unknown error 138
139:Unknown error 139
140:Unknown error 140
141:Unknown error 141
142:Unknown error 142
143:Unknown error 143
144:Unknown error 144
145:Unknown error 145
146:Unknown error 146
147:Unknown error 147
148:Unknown error 148
149:Unknown error 149

通过这个我们终于理解errno的含义了。。那天做的一个使用非阻塞connect式爬虫,无论如何也不好使,也不知道怎么解决,程序并没有出现段错误,最终定位在write套接字时就退出,而通过FD_ISSET测试此套接字可写,于是不知道怎么解决了。通过捕捉errno值,发现是104.而如果当时我可以知道errno=104是指“Connection reset by peer”,那么我就知道了网络爬虫式客户端需要增加对于SIGPIPE信号的处理了。。因为SIGPIPE默认处理方式是退出,改成自己添加信号处理函数或者使用忽略就可以了。。。

所以列出这些信息,一方面能对大家有所帮助,另一方面方便以后查询。

   1#ifndef _ASM_GENERIC_ERRNO_BASE_H
   2#define _ASM_GENERIC_ERRNO_BASE_H
   3
   4#define EPERM            1      /* Operation not permitted */
   5#define ENOENT           2      /* No such file or directory */
   6#define ESRCH            3      /* No such process */
   7#define EINTR            4      /* Interrupted system call */
   8#define EIO              5      /* I/O error */
   9#define ENXIO            6      /* No such device or address */
  10#define E2BIG            7      /* Argument list too long */
  11#define ENOEXEC          8      /* Exec format error */
  12#define EBADF            9      /* Bad file number */
  13#define ECHILD          10      /* No child processes */
  14#define EAGAIN          11      /* Try again */
  15#define ENOMEM          12      /* Out of memory */
  16#define EACCES          13      /* Permission denied */
  17#define EFAULT          14      /* Bad address */
  18#define ENOTBLK         15      /* Block device required */
  19#define EBUSY           16      /* Device or resource busy */
  20#define EEXIST          17      /* File exists */
  21#define EXDEV           18      /* Cross-device link */
  22#define ENODEV          19      /* No such device */
  23#define ENOTDIR         20      /* Not a directory */
  24#define EISDIR          21      /* Is a directory */
  25#define EINVAL          22      /* Invalid argument */
  26#define ENFILE          23      /* File table overflow */
  27#define EMFILE          24      /* Too many open files */
  28#define ENOTTY          25      /* Not a typewriter */
  29#define ETXTBSY         26      /* Text file busy */
  30#define EFBIG           27      /* File too large */
  31#define ENOSPC          28      /* No space left on device */
  32#define ESPIPE          29      /* Illegal seek */
  33#define EROFS           30      /* Read-only file system */
  34#define EMLINK          31      /* Too many links */
  35#define EPIPE           32      /* Broken pipe */
  36#define EDOM            33      /* Math argument out of domain of func */
  37#define ERANGE          34      /* Math result not representable */
  38
  39#endif


Linux网络编程socket错误分析

 

socket错误码:

 

EINTR: 4

阻塞的操作被取消阻塞的调用打断。如设置了发送接收超时,就会遇到这种错误。

只能针对阻塞模式的socket。读,写阻塞的socket时,-1返回,错误号为INTR。另外,如果出现EINTR即errno为4,错误描述Interruptedsystem call,操作也应该继续。如果recv的返回值为0,那表明连接已经断开,接收操作也应该结束。

 

ETIMEOUT:110

1、操作超时。一般设置了发送接收超时,遇到网络繁忙的情况,就会遇到这种错误。

2、服务器做了读数据做了超时限制,读时发生了超时。

3、错误被描述为“connect time out”,即“连接超时”,这种情况一般发生在服务器主机崩溃。此时客户 TCP 将在一定时间内(依具体实现)持续重发数据分节,试图从服务 TCP 获得一个 ACK 分节。当最终放弃尝试后(此时服务器未重新启动),内核将会向客户进程返回ETIMEDOUT 错误。如果某个中间路由器判定该服务器主机已经不可达,则一般会响应“destination unreachable”-“目的地不可达”的ICMP消息,相应的客户进程返回的错误是 EHOSTUNREACH 或ENETUNREACH。当服务器重新启动后,由于 TCP 状态丢失,之前所有的连接信息也不存在了,此时对于客户端发来请求将回应 RST。如果客户进程对检测服务器主机是否崩溃很有必要,要求即使客户进程不主动发送数据也能检测出来,那么需要使用其它技术,如配置 SO_KEEPALIVE Socket 选项,或实现某些心跳函数。

 

EAGAIN:

1、Send返回值小于要发送的数据数目,会返回EAGAIN和EINTR。

2、recv 返回值小于请求的长度时说明缓冲区已经没有可读数据,但再读不一定会触发EAGAIN,有可能返回0表示TCP连接已被关闭。

3、当socket是非阻塞时,如返回此错误,表示写缓冲队列已满,可以做延时后再重试.

4、在Linux进行非阻塞的socket接收数据时经常出现Resource temporarilyunavailable,errno代码为11(EAGAIN),表明在非阻塞模式下调用了阻塞操作,在该操作没有完成就返回这个错误,这个错误不会破坏socket的同步,不用管它,下次循环接着recv就可以。对非阻塞socket而言,EAGAIN不是一种错误。

 

EPIPE:

1、Socket 关闭,但是socket号并没有置-1。继续在此socket上进行send和recv,就会返回这种错误。这个错误会引发SIGPIPE信号,系统会将产生此EPIPE错误的进程杀死。所以,一般在网络程序中,首先屏蔽此消息,以免发生不及时设置socket进程被杀死的情况。

2、write(..) on a socket that has been closed at the other end willcause a SIGPIPE.

3、错误被描述为“broken pipe”,即“管道破裂”,这种情况一般发生在客户进程不理会(或未及时处理)Socket 错误,继续向服务 TCP 写入更多数据时,内核将向客户进程发送 SIGPIPE 信号,该信号默认会使进程终止(此时该前台进程未进行 core dump)。结合上边的 ECONNRESET 错误可知,向一个 FIN_WAIT2 状态的服务 TCP(已 ACK 响应 FIN 分节)写入数据不成问题,但是写一个已接收了 RST 的 Socket 则是一个错误。

 

EBADF:

read(..) or write(..) on a locally closedsocket will return EBADF

 

EFAULT:

地址错误。

 

EBUSY:

 

ECONNREFUSED:

1、拒绝连接。一般发生在连接建立时。

拔服务器端网线测试,客户端设置keep alive时,recv较快返回0, 先收到ECONNREFUSED (Connection refused)错误码,其后都是ETIMEOUT。

2、an error returned from connect(), so it can only occur in a client(if a client is defined as the party that initiates the connection

 

ECONNRESET:

1、在客户端服务器程序中,客户端异常退出,并没有回收关闭相关的资源,服务器端会先收到ECONNRESET错误,然后收到EPIPE错误。

2、连接被远程主机关闭。有以下几种原因:远程主机停止服务,重新启动;当在执行某些操作时遇到失败,因为设置了“keep alive”选项,连接被关闭,一般与ENETRESET一起出现。

3、远程端执行了一个“hard”或者“abortive”的关闭。应用程序应该关闭socket,因为它不再可用。当执行在一个UDP socket上时,这个错误表明前一个send操作返回一个ICMP“port unreachable”信息。

4、如果client关闭连接,server端的select并不出错(不返回-1,使用select对唯一一个socket进行non- blocking检测),但是写该socket就会出错,用的是send.错误号:ECONNRESET.读(recv)socket并没有返回错误。

5、该错误被描述为“connection reset by peer”,即“对方复位连接”,这种情况一般发生在服务进程较客户进程提前终止。当服务进程终止时会向客户 TCP 发送 FIN 分节,客户 TCP 回应 ACK,服务 TCP 将转入 FIN_WAIT2 状态。此时如果客户进程没有处理该 FIN (如阻塞在其它调用上而没有关闭 Socket 时),则客户 TCP 将处于 CLOSE_WAIT 状态。当客户进程再次向 FIN_WAIT2 状态的服务 TCP 发送数据时,则服务 TCP 将立刻响应 RST。一般来说,这种情况还可以会引发另外的应用程序异常,客户进程在发送完数据后,往往会等待从网络IO接收数据,很典型的如read 或 readline 调用,此时由于执行时序的原因,如果该调用发生在 RST 分节收到前执行的话,那么结果是客户进程会得到一个非预期的 EOF 错误。此时一般会输出“server terminatedprematurely”-“服务器过早终止”错误。

 

EINVAL:

无效参数。提供的参数非法。有时也会与socket的当前状态相关,如一个socket并没有进入listening状态,此时调用accept,就会产生EINVAL错误。

 

EMFILE:

打开了太多的socket。对进程或者线程而言,每种实现方法都有一个最大的可用socket数目处理,或者是全局的,或者是局部的。

 

EWOULDBLOCK:EAGAIN

资源暂时不可用。这个错误是从对非阻塞socket进行的不能立即结束的操作返回的,如当没有数据在队列中可以读时,调用recv。并不是fatal错误,稍后操作可以被重复。调用在一个非阻塞的SOCK_STREAMsocket 上调用connect时会产生这个错误,因为有时连接建立必须消耗一定的时间。

 

ENOTCONN

在一个没有建立连接的socket上,进行read,write操作会返回这个错误。出错的原因是socket没有标识地址。Setsoc也可能会出错。

 

ECONNRESET

 Connection reset by peer.

连接被远程主机关闭。有以下几种原因:远程主机停止服务,重新启动;当在执行某些操作时遇到失败,因为设置了“keep alive”选项,连接被关闭,一般与ENETRESET一起出现。

 

ECONNABORTED

1、软件导致的连接取消。一个已经建立的连接被host方的软件取消,原因可能是数据传输超时或者是协议错误。

2、该错误被描述为“software caused connection abort”,即“软件引起的连接中止”。原因在于当服务和客户进程在完成用于 TCP 连接的“三次握手”后,客户TCP 却发送了一个 RST (复位)分节,在服务进程看来,就在该连接已由 TCP 排队,等着服务进程调用 accept 的时候 RST 却到达了。POSIX 规定此时的 errno 值必须 ECONNABORTED。源自 Berkeley 的实现完全在内核中处理中止的连接,服务进程将永远不知道该中止的发生。服务器进程一般可以忽略该错误,直接再次调用accept。

当TCP协议接收到RST数据段,表示连接出现了某种错误,函数read将以错误返回,错误类型为ECONNERESET。并且以后所有在这个套接字上的读操作均返回错误。错误返回时返回值小于0。

 

ENETUNREACH

网络不可达。Socket试图操作一个不可达的网络。这意味着local的软件知道没有路由到达远程的host。

 

ENETRESET

网络重置时丢失连接。

由于设置了"keep-alive"选项,探测到一个错误,连接被中断。在一个已经失败的连接上试图使用setsockopt操作,也会返回这个错误。

 

EINPROGRESS:

操作正在进行中。一个阻塞的操作正在执行。

 

ENOTSOCK:

在非socket上执行socket操作。

 

EDESTADDRREQ:

需要提供目的地址。

在一个socket上的操作需要提供地址。如往一个ADDR_ANY 地址上进行sendto操作会返回这个错误。

 

EMSGSIZE:

消息体太长。

发送到socket上的一个数据包大小比内部的消息缓冲区大,或者超过别的网络限制,或是用来接收数据包的缓冲区比数据包本身小。

 

EPROTOTYPE

协议类型错误。标识了协议的Socket函数在不支持的socket上进行操作。如ARPA Internet

UDP协议不能被标识为SOCK_STREAM socket类型。

 

ENOPROTOOPT

该错误不是一个 Socket连接相关的错误。errno 给出该值可能由于,通过 getsockopt 系统调用来获得一个套接字的当前选项状态时,如果发现了系统不支持的选项参数就会引发该错误。

 

EPROTONOSUPPORT

不支持的协议。系统中没有安装标识的协议,或者是没有实现。如函数需要SOCK_DGRAM socket,但是标识了stream protocol.。

 

ESOCKTNOSUPPORT

Socket类型不支持。指定的socket类型在其addressfamily中不支持。如可选选中选项SOCK_RAW,但实现并不支持SOCK_RAW sockets。

 

EOPNOTSUPP

 Operation not supported.

 

The attempted operation is not supported forthe type of object referenced. Usually this occurs when a socket descriptor toa socket that cannot support this operation, for example, trying to accept aconnection on a datagram socket.

 

EPFNOSUPPORT

 Protocol family not supported.

 

The protocol family has not been configuredinto the system or no implementation for it exists. Has a slightly differentmeaning to EAFNOSUPPORT, but is interchangeable in most cases, and all WindowsSockets functions that return one of these specify EAFNOSUPPORT.

 

EAFNOSUPPORT

 Address family not supported by protocolfamily.

 

An address incompatible with the requestedprotocol was used. All sockets are created with an associated "addressfamily" (i.e. AF_INET for Internet Protocols) and a generic protocol type(i.e. SOCK_STREAM). This error will be returned if an incorrect protocol isexplicitly requested in the socket call, or if an address of the wrong familyis used for a socket, e.g. in sendto.

 

EADDRINUSE

 Address already in use.

 

Only one usage of each socket address(protocol/IP address/port) is normally permitted. This error occurs if anapplication attempts to bind a socket to an IP address/port that has alreadybeen used for an existing socket, or a socket that wasn't closed properly, orone that is still in the process of closing. For server applications that needto bind multiple sockets to the same port number, consider usingsetsockopt(SO_REUSEADDR). Client applications usually need not call bind at all- connect will choose an unused port automatically. When bind is called with awild-card address (involving ADDR_ANY), a EADDRINUSE error could be delayeduntil the specific address is "committed." This could happen with acall to other function later, including connect, listen, Connect or JoinLeaf.

 

EADDRNOTAVAIL

 Cannot assign requested address.

 

The requested address is not valid in itscontext. Normally results from an attempt to bind to an address that is notvalid for the local machine. This can also result from connect, sendto,Connect, JoinLeaf, or SendTo when the remote address or port is not valid for aremote machine (e.g. address or port 0).

 

ENETDOWN

 Network is down.

 

A socket operation encountered a deadnetwork. This could indicate a serious failure of the network system (i.e. theprotocol stack that the WinSock DLL runs over), the network interface, or thelocal network itself.

 

ENOBUFS

 Nobuffer space available.

 

An operation on a socket could not beperformed because the system lacked sufficient buffer space or because a queuewas full.

 

EISCONN

 Socket is already connected.

 

A connect request was made on an alreadyconnected socket. Some implementations also return this error if sendto iscalled on a connected SOCK_DGRAM socket (For SOCK_STREAM sockets, the toparameter in sendto is ignored), although other implementations treat this as alegal occurrence.

 

连接过程可能出现的错误情况有:

(1) 如果客户机TCP协议没有接收到对它的SYN数据段的确认,函数以错误返回,错误类型为ETIMEOUT。通常TCP协议在发送SYN数据段失败之后,会多次发送SYN数据段,在所有的发送都高中失败之后,函数以错误返回。

注:SYN(synchronize)位:请求连接。TCP用这种数据段向对方TCP协议请求建立连接。在这个数据段中,TCP协议将它选择的初始序列号通知对方,并且与对方协议协商最大数据段大小。SYN数据段的序列号为初始序列号,这个SYN数据段能够被确认。当协议接收到对这个数据段的确认之后,建立TCP连接。

(2) 如果远程TCP协议返回一个RST数据段,函数立即以错误返回,错误类型为ECONNREFUSED。当远程机器在SYN数据段指定的目的端口号处没有服务进程在等待连接时,远程机器的TCP协议将发送一个RST数据段,向客户机报告这个错误。客户机的TCP协议在接收到RST数据段后不再继续发送SYN数据段,函数立即以错误返回。

注:RST(reset)位:表示请求重置连接。当TCP协议接收到一个不能处理的数据段时,向对方TCP协议发送这种数据段,表示这个数据段所标识的连接出现了某种错误,请求TCP协议将这个连接清除。有3种情况可能导致TCP协议发送RST数据段:(1)SYN数据段指定的目的端口处没有接收进程在等待;(2)TCP协议想放弃一个已经存在的连接;(3)TCP接收到一个数据段,但是这个数据段所标识的连接不存在。接收到RST数据段的TCP协议立即将这条连接非正常地断开,并向应用程序报告错误。

(3) 如果客户机的SYN数据段导致某个路由器产生“目的地不可到达”类型的ICMP消息,函数以错误返回,错误类型为EHOSTUNREACH或ENETUNREACH。通常TCP协议在接收到这个ICMP消息之后,记录这个消息,然后继续几次发送SYN数据段,在所有的发送都告失败之后,TCP协议检查这个ICMP消息,函数以错误返回。

注:ICMP:Internet 消息控制协议。Internet的运行主要是由Internet的路由器来控制,路由器完成IP数据包的发送和接收,如果发送数据包时发生错误,路由器使用 ICMP协议来报告这些错误。ICMP数据包是封装在IP数据包的数据部分中进行传输的,其格式如下:

类型

校验和

数据

0 8 16 24 31

类型:指出ICMP数据包的类型。

代码:提供ICMP数据包的进一步信息。

校验和:提供了对整个ICMP数据包内容的校验和。

ICMP数据包主要有以下类型:

(1) 目的地不可到达:A、目的主机未运行;B、目的地址不存在;C、路由表中没有目的地址对应的条目,因而路由器无法找到去往目的主机的路由。

(2) 超时:路由器将接收到的IP数据包的生存时间(TTL)域减1,如果这个域的值变为0,路由器丢弃这个IP数据包,并且发送这种ICMP消息。

(3) 参数出错:当IP数据包中有无效域时发送。

(4) 重定向:将一条新的路径通知主机。

(5) ECHO请求、ECHO回答:这两条消息用语测试目的主机是否可以到达。请求者向目的主机发送ECHO请求ICMP数据包,目的主机在接收到这个ICMP数据包之后,返回ECHO回答ICMP数据包。

(6) 时戳请求、时戳回答:ICMP协议使用这两种消息从其他机器处获得其时钟的当前时间。

 

调用函数connect的过程中,当客户机TCP协议发送了SYN数据段的确认之后,TCP状态由CLOSED状态转为SYN_SENT状态,在接收到对 SYN数据段的确认之后,TCP状态转换成ESTABLISHED状态,函数成功返回。如果调用函数connect失败,应该用close关闭这个套接字描述符,不能再次使用这个套接字描述符来调用函数connect。

 

connect函数的出错处理:

(1)ETIMEOUT-connection timed out 目的主机不存在,没有返回任何相应,例如主机关闭

(2)ECONNREFUSED-connection refused(硬错)到达目的主机后,由于各种原因建立不了连接,主机返回RST(复位)响应,例如主机监听进程未启用,tcp取消连接等

(3)EHOSTTUNREACH-no route to host(软错)路由上引发了一个目的地不可达的ICMP错误

 

其中(1)(3),客户端会进行定时多次重试,一定次数后才返回错误。另外,当connect连接失败时,sockfd套接口不可用,必须关闭后重新socket分配才行。

 

getsockopt 和 setsockopt 还可能引发以下错误:

 

getsockopt/setsockopt(2) man page 写道

ERRORS

 

The getsockopt() and setsockopt() systemcalls will succeed unless:

 

[EBADF] The argument socket is not a validfile descriptor.

[EFAULT] The address pointed to by option_valueis not in a valid part of the process dress space. For getsockopt(), this errormay also be returned if option_len is not in a valid part of the processaddress space.

[EINVAL] The option is invalid at the levelindicated.

[ENOBUFS]Insufficient memory buffers areavailable.

[ENOPROTOOPT] The option is unknown at thelevel indicated.

[ENOTSOCK] The argument socket is not asocket (e.g., a plain file).

 

The setsockopt() system call will succeedunless:

 

[EDOM] The argument option_value isout of bounds.

[EISCONN]socket is already connected and aspecified option cannot be set while this is the case.




0 0