Socket operation on non-sockets, client server program in C

I am new to socket programming and I am trying to write a simple socket that plugs into another socket on my PC ( nc -l 35353 )

I keep getting an error when trying to bind a socket, and I don't know how to debug it.


UPDATE:. The cell call returns 0 as a file descriptor, although the man page does not say that it is illegal, I thought unix / linux reserve fd 0, 1 and 2 for stdin, stdout and stderr by default. I am not sure if this is due to the binding error that I see, I just felt that this might be appropriate.

Here is the code

 #include<stdio.h> #include<stdlib.h> #include<string.h> #include<netinet/in.h> #include<sys/types.h> #include<sys/socket.h> //typedef struct sockaddr_in sockaddr_in; int main() { int sock_fd; if( sock_fd = socket(AF_INET, SOCK_STREAM, 0) < 0) { perror("Socket Creation error!\n"); return 1; } struct sockaddr_in myaddr; memset((char*)&myaddr, 0, sizeof(myaddr)); myaddr.sin_family = AF_INET; uint32_t myip = (127<<24)|(0<<16)|(0<<8)|1; myaddr.sin_addr.s_addr = htonl(myip); myaddr.sin_port = htons(1337); int binderror = bind(sock_fd, (struct sockaddr*)&myaddr, sizeof(myaddr)); printf("bind error %d\n",binderror); if( binderror < 0) { perror("Bind Error!\n"); return 1; } struct sockaddr_in serveraddr; memset((char*)&serveraddr, 0, sizeof(serveraddr)); serveraddr.sin_family = AF_INET; serveraddr.sin_port = htons(35353); //unsigned char serverip[] = {127,0,0,1}; uint32_t serverip = (127<<24)|(0<<16)|(0<<8)|1; serveraddr.sin_addr.s_addr = htonl(serverip); if( connect(sock_fd, (struct sockaddr*)&serveraddr, sizeof(serveraddr)) < 0 ){ perror("Could not connect\n"); return 0; } } 
+4
source share
1 answer

Your problem here is

 if( sock_fd = socket(AF_INET, SOCK_STREAM, 0) < 0) 

This is an old priority, if ( a = b == c ) is how to say if ( a = ( b == c ))
It calls the function, comparing it with -1 and assigning the logical result sock_fd

What do you think -

 if( (sock_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) 
+3
source

All Articles