Page 82

Beej's Guide to Network Programming

9.16. perror(), strerror() Print an error as a human-readable string Prototypes #include <stdio.h> #include <string.h>

// for strerror()

void perror(const char *s); char *strerror(int errnum);

Description Since so many functions return -1 on error and set the value of the variable errno to be some number, it would sure be nice if you could easily print that in a form that made sense to you. Mercifully, perror() does that. If you want more description to be printed before the error, you can point the parameter s to it (or you can leave s as NULL and nothing additional will be printed.) In a nutshell, this function takes errno values, like ECONNRESET, and prints them nicely, like â&#x20AC;&#x153;Connection reset by peer.â&#x20AC;? The function strerror() is very similar to perror(), except it returns a pointer to the error message string for a given value (you usually pass in the variable errno.) Return Value

strerror() returns a pointer to the error message string.

Example int s; s = socket(PF_INET, SOCK_STREAM, 0); if (s == -1) { // some error has occurred // prints "socket error: " + the error message: perror("socket error"); } // similarly: if (listen(s, 10) == -1) { // this prints "an error: " + the error message from errno: printf("an error: %s\n", strerror(errno)); }

See Also errno

78

Beej's Guide To Network Programming  
Beej's Guide To Network Programming  

A through introduction to the aspects of network programming

Advertisement