Reputation: 11
I am following a c++ networking tutorial, winsock.
But my code I have written so far does not entirely work, what am I doing wrong?
my "main.cpp"
#include "main.h"
using namespace std;
int winsock()
{
//variables
const int winsock_version = 2;
WSAData wsa;
SOCKET sok;
SOCKADDR_IN server;
//start up
WSAStartup(MAKEWORD(winsock_version,0), &wsa);
sok = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
//check startup
if(WSAStartup(MAKEWORD(winsock_version,0), &wsa) != 0)
{
cout << "An error occured during startup! \n";
WSACleanup();
return -1;
}
//check version
if (LOBYTE(wsa.wVersion) < winsock_version)
{
cout << "Your version of winsock is too low!\n";
cout << "\nWinsock 2.0 or above is required.";
return -1;
}
//check if socket is valid
if (sok == INVALID_SOCKET)
{
cout << "Invalid socket!";
return -1;
}
//set connection type
server.sin_family = AF_INET;
//set port
server.sin_port = htons(80);
//set adress to connect to
server.sin_addr.S_un.S_addr = INADDR_ANY;
//connect
connect(sok,(sockaddr*)(&server), sizeof(server));
//bind socket
bind(sok, (sockaddr*)(&server), sizeof(server));
if(connect(sok,(sockaddr*)(&server), sizeof(server)) !=0)
{
cout << "error during connecting! \n";
WSACleanup();
closesocket(sok);
return -1;
}
cout << "Connection was made!";
//clean up
WSACleanup();
closesocket(sok);
if (WSACleanup() !=0 || closesocket(sok) !=0)
{
cout << "Clean up failed! \n";
return -1;
}
return 0;
}
int main()
{
winsock();
}
and my "main.h"
#ifndef MAIN_H_INCLUDED
#define MAIN_H_INCLUDED
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
// std libs
#include <iostream>
#include <fstream>
#include <string>
//windows
#include <windows.h>
//networking libs
#include <winsock2.h>
// layout engine
#endif // MAIN_H_INCLUDED
When I run the program it says "error during connecting!", so that means I have some kind of error.
I use code::blocks as my IDE.
What am I doing wrong?
Upvotes: 1
Views: 977
Reputation: 27854
You cannot connect to INADDR_ANY
. Specify a IP address.
Why are you calling WSAStartup()
twice?
And you don't have to use bind()
to perform a connect()
unless its strictily important that your local port must be specified (like in SMB protocol).
There are plenty of exemples on how to use WinSock to connect, read them.
Upvotes: 2