Getting an error code while creating a socket on Linux
I am doing socket programming on Linux and I am wondering how to get the error code when the socket functions (...); fails.
for example, for the "getaddrinfo" function, I can do this:
//Resolve the server address and port
result = (struct addrinfo *) calloc(1, sizeof(struct addrinfo));
iResult = getaddrinfo("google.com", DEFAULT_PORT, &hints, &result);
if (iResult != 0){
printf("%d\n", iResult);
fprintf(stderr, "getaddrinfo failed: %s\n", gai_strerror(iResult));
getchar();
exit(EXIT_FAILURE);
}
However, I want to do a similar thing using the socket (...) function.
According to this: http://linux.die.net/man/2/socket
the function returns -1 on failure and sets errno to the appropriate error number. How can I access this "errno"? This is my code:
int connectSocket = 0;
connectSocket = socket(AF_INET, SOCK_STREAM, 0);
printf("%d\n", connectSocket);
if (connectSocket == -1){
printf("socket failed with error: %s\n", error_string); //TODO: HELP DECLARING error_string
getchar();
exit(EXIT_FAILURE);
}
source to share
errno
is a global thread variable defined in <errno.h>
. The man page for many of the library functions specifies that they return -1 on error and set errno
.
You can convert the value errno
to a useful string using a function strerror
.
In general, you should do the code like this:
#include <stdio.h>
#include <errno.h>
int main(void) {
int s;
s = socket(...);
if (s < 0) {
fprintf(stderr, "socket() failed: %s\n", strerror(errno));
exit(1);
}
}
As an alternative to glibc printf
, and friends support a format specifier %m
which is replaced with strerror(errno)
(no argument required). So the above example can be replaced with:
if (s < 0) {
fprintf(stderr, "socket() failed: %m\n");
exit(1);
}
And to make things easier, there is a function perror
that prints a message like the one above.
if (s < 0) {
perror("socket");
exit(1);
}
To wrap it all up - error handling doesn't have to be complicated and verbose. By < 0
putting the socket call and test for in one statement, the above code could look like this and you become a real UNIX pro:
#include <stdio.h>
#include <errno.h>
int main(void) {
int s;
if ((s = socket(...)) < 0) {
perror("socket");
exit(1);
}
}
source to share
Add #include <errno.h>
and you can read the global variable errno
.
connectSocket = socket(AF_INET, SOCK_STREAM, 0);
if (connectSocket < 0) {
if (errno == EACCESS) ...
You can use perror
in stdio.h
to print the error message based on the value errno
or you can use strerror
in string.h
to access the line describing the error code
connectSocket = socket(AF_INET, SOCK_STREAM, 0);
if (connectSocket < 0) {
perror("socket");
exit(EXIT_FAILURE);
}
source to share