13.07.2015 Views

Beej's Guide to Network Programming Using Internet Sockets

Beej's Guide to Network Programming Using Internet Sockets

Beej's Guide to Network Programming Using Internet Sockets

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Beej’s <strong>Guide</strong> <strong>to</strong> <strong>Network</strong> <strong>Programming</strong> <strong>Using</strong> <strong>Internet</strong> <strong>Sockets</strong> 578.13. perror(), strerror()Print an error as a human-readable stringPro<strong>to</strong>types#include void perror(const char *s);#include char *strerror(int errnum);DescriptionSince so many functions return -1 on error and set the value of the variable errno <strong>to</strong> be somenumber, it would sure be nice if you could easily print that in a form that made sense <strong>to</strong> you.Mercifully, perror() does that. If you want more description <strong>to</strong> be printed before the error,you can point the parameter s <strong>to</strong> it (or you can leave s as NULL and nothing additional will beprinted.)In a nutshell, this function takes errno values, like ECONNRESET, and prints them nicely, like“Connection reset by peer.”The function strerror() is very similar <strong>to</strong> perror(), except it returns a pointer <strong>to</strong> the errormessage string for a given value (you usually pass in the variable errno.)Return Valuestrerror() returns a pointer <strong>to</strong> the error message string.Exampleint 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 Alsoerrno

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!