I'm doing some socket programming in Linux and am wondering how to get the error code when the function socket(...); 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 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 do i access this "errno" though? This is my code so far:
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);
}
errno(3)andstrerror(3)manual pages.addrinfothat you pass in the last parameter ofgetaddrinfo(). It will allocate theaddrinfofor you, which you pass tofreeaddrinfo()to free it:result = NULL; iResult = getaddrinfo(..., &result); if (iResult == 0) { ...; freeaddrinfo(result); }