How to connect to the server on с

Viewed 24

I have the code but it doesn't work and I don't understand why? What do I need to do to connect to the server and how do I send messages to it in the future? https://cdn.discordapp.com/attachments/503211497766256642/968519683030523964/unknown.png Here is a photo of my mistakes. Most mistakes in the first part

#include <stdio.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, “Ws2_32.lib”)

WSADATA wsaData;    
int iResult;


iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);     

if (iResult != 0)     
{
     printf("WSAStartup failed: %d\n", iResult);
     return 1;
}

struct addrinfo *result = NULL, *ptr = NULL;     
struct addrinfo hints;

ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP; 
iResult = getaddrinfo("147.175.115.34", "777", &hints, &result);
if (iResult != 0)     
{
     printf("getaddrinfo failed: %d\n", iResult);
     WSACleanup();
     return 1;
}
else 
printf("getaddrinfo fail…\n");

SOCKET ConnectSocket = INVALID_SOCKET;
ptr = result;

ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,ptr->ai_protocol);

if (ConnectSocket == INVALID_SOCKET)      
{
     printf("Error at socket(): %ld\n", WSAGetLastError());
     freeaddrinfo(result);
     WSACleanup();
     return 1;
}
else
printf("Error at socke occur…\n");

iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);

if (iResult == SOCKET_ERROR)     
printf("Not connected to server…\n");
else
printf("Connected to server!\n");

if (iResult == SOCKET_ERROR)    
{
    closesocket(ConnectSocket);
    ConnectSocket = INVALID_SOCKET;
    WSACleanup();
    return 1;
}

Sleep(250);

char sendbuf[4096];

iResult = send(ConnectSocket, sendbuf, (int)strlen(sendbuf), 0);
if (iResult == SOCKET_ERROR)
{
     printf("send failed: %d\n", WSAGetLastError());
     closesocket(ConnectSocket);
     WSACleanup();
     return 1;
} 

printf("Bytes Sent: %ld\n", iResult);

#define DEFAULT_BUFLEN 4096 

int recvbuflen = DEFAULT_BUFLEN;
char recvbuf[DEFAULT_BUFLEN];


iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);     
if ( iResult > 0 )
printf("Bytes received: %d\n", iResult);
else if ( iResult == 0 )
printf("Connection closed\n");     
else
printf("recv failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
0 Answers
Related