Socket return 'No such file or directory "

Linux GCC 4.4.2

I do socket programming.

However, I keep getting this error when I try to assign sockfd from a socket function.

" Socket operation on non-socket" 

Thanks so much for any advice,

 #if defined(linux) #include <pthread.h> /* Socket specific functions and constants */ #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <errno.h> #endif #include "server.h" #include "cltsvr_ults.h" /* Listens for a connection on the designated port */ void wait_client() { struct addrinfo add_info, *add_res; int sockfd; /* Load up the address information using getaddrinfo to fill the struct addrinfo */ memset(&add_info, 0, sizeof(add_info)); /* Use either IPv4 or IPv6 */ add_info.ai_family = AF_UNSPEC; add_info.ai_socktype = SOCK_STREAM; /* Fill in my IP address */ add_info.ai_flags = AI_PASSIVE; /* Fill the struct addrinfo */ int32_t status = 0; if(status = getaddrinfo(NULL, "6000", &add_info, &add_res) != 0) { fprintf(stderr, "getaddrinfo [ %s ]\n", gai_strerror(status)); return; } if((sockfd = (socket(add_res->ai_family, add_res->ai_socktype, add_res->ai_protocol)) == -1)) { fprintf(stderr, "Socket failed [ %s ]\n", strerror(errno)); return; } /* Bind to the port that has been assigned by getaddrinfo() */ if(bind(sockfd, add_res->ai_addr, add_res->ai_addrlen) != 0) { fprintf(stderr, "Bind failed [ %s ]\n", strerror(errno)); return; } printf("Listening for clients\n"); } 

Change == coding in old school method

  int32_t sockfd = 0; struct sockaddr_in my_addr; memset(&my_addr, 0, sizeof(my_addr)); my_addr.sin_family = AF_INET; my_addr.sin_port = htons(6000); my_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); sockfd = socket(PF_INET, SOCK_STREAM, 0); if(sockfd == -1) { fprintf(stderr, "Socket failed [ %s ]\n", strerror(errno)); return; } if(bind(sockfd, (struct sockaddr *) &my_addr, sizeof(my_addr)) == -1) { fprintf(stderr, "Bind failed [ %s ]\n", strerror(errno)); return; } 
+4
source share
2 answers

The main problem is that you have the wrong check if socket () has an error. socket () will return -1 on error, not 0 on success. You can get a good socket value (2, 3, etc.) and treat it like an error.

There is also a second problem in how you copy your code into brackets. When you write:

 if (sockfd = socket(add_res->ai_family, add_res->ai_socktype, add_res->ai_protocol) != 0) 

This is considered as:

 if (sockfd = (socket(add_res->ai_family, add_res->ai_socktype, add_res->ai_protocol) != 0)) 

Thus, sockfd will not be assigned the return value of the socket, but its comparison value is against 0. Correcting both problems, you should write:

 if ((sockfd = socket(add_res->ai_family, add_res->ai_socktype, add_res->ai_protocol)) == -1) 
+12
source

I believe that you need to specify the type of socket you want. When you speak:

 add_info.ai_family = AF_UNSPEC; 

you should say:

 add_info.ai_family = AF_INET; 
0
source

All Articles