B
B
Beej's Guide to Network Programming 正體中文版
Search…
B
B
Beej's Guide to Network Programming 正體中文版
簡介
聯絡譯者
簡體中文版
中文授權
原著資訊
進階資料
導讀
何謂 Socket
IP address、結構與資料轉換
從 IPv4 移植為 IPv6
System call 或 Bust
Client-Server 基礎
進階技術
常見的問題
Man 使用手冊
accept()
bind()
connect()
close()
getaddrinfo(), freeaddrinfo(), gai_strerror()
gethostname()
gethostbyname(), gethostbyaddr()
getnameinfo()
getpeername()
errno
fcntl()
htons(), htonl(), ntohs(), ntohl()
inet_ntoa(), inet_aton(), inet_addr
inet_ntop(), inet_pton()
listen()
perror(), strerror()
poll()
recv(), recvfrom()
select()
setsockopt(), getsockopt()
send(), sendto()
shutdown()
socket()
struct sockaddr and pals
參考資料
原著誌謝
譯者誌謝
Powered By
GitBook
perror(), strerror()
輸出易讀的錯誤訊息字串
函式原型
1
#include <stdio.h>
2
#include <string.h> // strerror() 需要
3
4
void perror(const char *s);
5
char *strerror(int errnum);
Copied!
說明
因為大多的函式錯誤都是傳回 -1,並設定 errno 變數值為某個數,如果你還可以很簡單地印出適合你的格式,這樣就更完美了。
感謝上天,perror() 可以。如果你想要在錯誤訊息前加上一些敘述,你可以將訊息透過 s 參數傳遞(或你可以將 s 參數設定為 NULL,這樣就不會印出額外的訊息)。
簡單說,這個函式透過 errno 值,比如:ECONNRESET,然後印出比較有意義的訊息,像是 "Connection reset by peer"(對方重置連線)。
函式 strerror() 類似 perror(),不同之處是 strerror() 會依據所給的值,傳回一個指向錯誤訊息的指標(通常你會傳 errno 變數)。
傳回值
strerror() 傳回指向錯誤訊息字串的指標。
範例
1
int s;
2
3
s = socket(PF_INET, SOCK_STREAM, 0);
4
5
if (s == -1) { // some error has occurred
6
// 印出 "socket error: " + 錯誤訊息:
7
perror("socket error");
8
}
9
10
// 類似的
11
if (listen(s, 10) == -1) {
12
// 這會印出 "一個錯誤: " + errno 的錯誤訊息:
13
printf("an error: %s\n", strerror(errno));
14
}
Copied!
參考
errno
Previous
listen()
Next
poll()
Last modified
1yr ago
Copy link
Contents
函式原型
說明
傳回值
範例
參考