Reputation: 1086
I have written a client and server using winsock2. The server seems to run fine but when I run the client it returns the 10038 error code for "Socket operation on nonsocket" immediately. Not sure why its doing that at is will create the socket with returning an error.
Here is the code for the client, It fails on the connect function call:
#include <stdio.h>
#include <winsock2.h>
#include <time.h>
#pragma comment(lib,"ws2_32.lib") //Winsock Library
int main(int *argc, char **argv){
struct sockaddr_in server, client;
char server_reply[2000];
WSADATA wsa;
int result = WSAStartup(MAKEWORD(2,2),&wsa);
SOCKET sock, newSock;
if ((sock = socket(AF_INET, SOCK_STREAM, 0) == INVALID_SOCKET)){
printf("Failed to create socketwith error code : %d" , WSAGetLastError());
}
else{
printf("Socket created\n");
}
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_family = AF_INET;
server.sin_port = htons(8080);
if((newSock = connect(sock , (struct sockaddr *)&server , sizeof(server)) == INVALID_SOCKET )){
printf("connect failed with error code : %d" , WSAGetLastError());
}
else{
printf("connected");
}
closesocket(socket);
WSACleanup();
return 0;
}
The code for the server which I believe works:
#include<io.h>
#include<stdio.h>
#include<winsock2.h>
#pragma comment(lib,"ws2_32.lib") //Winsock Library
int main(int argc , char *argv[])
{
WSADATA wsa;
SOCKET s , new_socket;
struct sockaddr_in server , client;
int c;
char message[54];
printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
{
printf("Failed. Error Code : %d",WSAGetLastError());
return 1;
}
printf("Initialised.\n");
//Create a socket
if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
{
printf("Could not create socket : %d" , WSAGetLastError());
}
printf("Socket created.\n");
//Prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons( 8080 );
//Bind
if( bind(s ,(struct sockaddr *)&server , sizeof(server)) == SOCKET_ERROR)
{
printf("Bind failed with error code : %d" , WSAGetLastError());
return 1;
}
puts("Bind done");
//Listen to incoming connections
listen(s , 3);
//Accept and incoming connection
puts("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);
while( (new_socket = accept(s , (struct sockaddr *)&client, &c)) != INVALID_SOCKET )
{
recv(s, message, 2000, 0);
printf(message);
}
if (new_socket == INVALID_SOCKET)
{
printf("accept failed with error code : %d" , WSAGetLastError());
return 1;
}
closesocket(s);
WSACleanup();
return 0;
}
Upvotes: 1
Views: 172
Reputation: 18420
You are setting the parentheses wrong:
if ((sock = socket(AF_INET, SOCK_STREAM, 0) == INVALID_SOCKET))
assigns 0 to "sock", you want the following:
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
to have the comparison after the assignment, instead of assigning the result of the comparison. This is a matter of operator precedence, ==
"winning" over =
.
Upvotes: 2