irsock programming and visual c++ 12 - c++

I want develop some irDA sockets applications, I am using:
compiler: visual c++ 2013.
platform: windows 7 x64
It seem s to me that something went wrong:
#include <iostream>
#include <winsock2.h>
#include <af_irda.h>
using std::cout;
using std::endl;
#pragma comment(lib,"ws2_32.lib")
int main()
{
WSADATA wSaData;
WSAStartup(MAKEWORD(2,2),&wSaData);
int sockServ = socket(AF_IRDA, SOCK_STREAM, 0);
if(sockServ == SOCKET_ERROR) //this condition succeeds which means creating socket failed!??
cout<<"Failed to create socket! " << WSAGetLastError() << endl;
DEVICELIST devLst;
devLst. = 0;
int len = sizeof(devLst;);
int rc = getsockopt(sockServ,SOL_IRLMP,IRLMP_ENUMDEVICES,(char*)&devLst,&devLst);
//rc also = -1;
WCE_IAS_QUERY wceIasQuery; // Error: WCE_IAS_QUERY is undefined
//...
return 0;
}
I'd like explanation:
1- why socket creation failed?
2- why getsockopt failed?
3- why WCE_IAS_QUERY is undeclared identifier?
4- what are the pre-requisites for irSock programming?
thank you guys!

Related

Using std::thread for send and recive data from TCP socket

I'm developing a TCP socket client. I am trying to write a client that have individual thread for send and receive data. but when I use thread, get a runtime error.
The process goes like this:
main.cpp:
#include <iostream>
#include <thread>
#include <string>
#include <chrono>
#include <WS2tcpip.h>
#pragma comment(lib, "ws2_32.lib")
#include "TCPConnection.h"
SOCKET sock;
void SendRecive(SOCKET *isock) {
// Do-While loop to send and recive data
char buf[4096];
while (true) {
// Prompt the user for some text
cout << "> ";
// Wait for response
ZeroMemory(buf, 4096);
auto byteRecived = recv(*isock, buf, 4096, 0);
if (byteRecived <= 0) continue;
// Echo response to console
cout << "SERVER> " << string(buf, 0, byteRecived) << endl;
}
}
using namespace std;
int main() {
TCPConnection tcpconn("192.168.1.4", 7705, &sock);
SendRecive(&sock);
return 0;
}
TCPConnection.h:
//
// Created by Hamed on 8/21/2021.
//
#ifndef TCPCLIENT_TCPCONNECTION_H
#define TCPCLIENT_TCPCONNECTION_H
#include <iostream>
#include <thread>
#include <string>
#include <WS2tcpip.h>
#pragma comment(lib, "ws2_32.lib")
using namespace std;
class TCPConnection {
public:
SOCKET *isock;
TCPConnection(string ServerIPAddress, int ServerPort, SOCKET *sock);
~TCPConnection();
};
#endif //TCPCLIENT_TCPCONNECTION_H
TCPConnection.cpp:
#include "TCPConnection.h"
TCPConnection::TCPConnection(string ServerIPAddress, int ServerPort, SOCKET *sock) {
// Initialize WinSock
WSAData data{};
WORD ver = MAKEWORD(2, 2);
int wsResult = WSAStartup(ver, &data);
if (wsResult != 0) {
cerr << "Can't start winsock, Err #" << wsResult << endl;
return;
}
// Create socket
*sock = socket(AF_INET, SOCK_STREAM, 0);
if (*sock == INVALID_SOCKET) {
cerr << "Can't create socket, Err #" << WSAGetLastError() << endl;
WSACleanup();
return;
}
// Fill in a hint structure
sockaddr_in hint{};
hint.sin_family = AF_INET;
hint.sin_port = htons(ServerPort);
inet_pton(AF_INET, ServerIPAddress.c_str(), &hint.sin_addr);
// connect to server
int connResult = connect(*sock, (sockaddr *) &hint, sizeof(hint));
if (connResult == SOCKET_ERROR) {
cerr << "Can't connect to server, Err #" << WSAGetLastError() << endl;
closesocket(*sock);
WSACleanup();
return;
}
isock = sock;
}
TCPConnection::~TCPConnection() {
// Gracefully close down everything
closesocket(*isock);
WSACleanup();
}
this code working properly but when I change "main.cpp" to use thread like this:
int main() {
TCPConnection tcpconn("192.168.1.4", 7705, &sock);
thread DoRunTCPRecive(SendRecive,&sock);
return 0;
}
I get "Microsoft Visual C++ Runtime Library" debug error when runing app.
Update:
Actually I want to have a function for send and have another function for receive data . but when I use join, my code stay on current function and I can't run another code after that.
you should join the thread after create it
thread DoRunTCPRecive(SendRecive,&sock);
DoRunTCPRecive.join()

Why got invalid socket in eclipse debug mode only?

In eclipse C++ I got an invalid socket when starting the debug mode.
The error is WSAEPROVIDERFAILEDINIT.
I got this error when using the debugger only. Starting with run, the creation of the socket is successful.
Under VisualStudio the same code runs in debug and release mode.
Debugging with eclipse and mingw works fine when no socket is used.
It seems to be a problem with the configuration of gdb, because eclipse is using the same exe independent if I start with run or with debug (there is no change of the timestamp which I change the configuration).
The configuration is: eclipse 4.6.3, Mingw32-gcc-g++ V6.3.0-1, I linked the libws2_32 from \Mingw\lib, under Windows 10, 64bit.
\Mingw\bin is added to the path variable under Windows and in Eclipse itself.
This is the the code:
#include <iostream>
#include <windows.h>
#include <winsock2.h>
using namespace std;
int main()
{
WORD sockVer = MAKEWORD(2, 0);
WSADATA wsaData;
SOCKET listener;
SOCKADDR_IN servInfo;
servInfo.sin_family = AF_INET;
servInfo.sin_addr.s_addr = INADDR_ANY;
servInfo.sin_port = htons(80);
WSAStartup(sockVer, &wsaData);
listener = socket(servInfo.sin_family, SOCK_STREAM, IPPROTO_TCP);
if (listener == INVALID_SOCKET)
{
int lastErr = WSAGetLastError();
cout << "Error = " << lastErr << endl;
}
else
{
cout << "Listener = " << listener << endl;
}
return 0;
}
I found it by myself. I removed the workspace and created a new one. With the new one it runs. I don't know what happend.

Visual C++ program complains about net framework

I wrote a simple client program in Visual C++ 2010 which connects to a client using winsock. When I try to run this program on another computer, it complains about missing Net Framework.
I wonder why that would be the case? What's in my code that requires net framework?
The error message:
application, you must first install one of the following versions of
the .NET Framework v4.0...etc
Here's my code
#pragma once
#pragma comment(lib, "Ws2_32.lib")
#include "stdafx.h"
#include <sdkddkver.h>
#include <WinSock2.h>
#include <Windows.h>
#include <iostream>
#include <string>
#include <time.h>
#include <cstring>
#include <sstream>
#define SCK_VERSION2 0x020
using namespace std;
void main() {
long Successful;
WSAData WinSockData;
WORD DLLVersion;
DLLVersion = MAKEWORD(2,1);
Successful = WSAStartup(DLLVersion, &WinSockData);
int sd,rcv,i,myint = 1;
hostent *host = gethostbyname("localhost");
char * myhostadd = inet_ntoa (*((struct in_addr *) host->h_addr_list[0]));
string memzi2,memzi,Converter;
char Message[200],tell[200] = "haa";
SOCKADDR_IN Address;
SOCKET sock;
sock = socket(AF_INET,SOCK_STREAM,NULL);
Address.sin_addr.s_addr = inet_addr(myhostadd);
Address.sin_family = AF_INET;
Address.sin_port = htons(7177);
cout << "Connecting to server...";
Successful = connect(sock, (SOCKADDR*)&Address, sizeof(Address));
u_long iMode=1;
ioctlsocket(sock,FIONBIO,&iMode);
if (Successful == 0) {
cout << "Connected. "<< endl;
for (;;++i) {
std::stringstream convert2;
convert2 << myint;
memzi2 = convert2.str();
std::cout << "Client: " << memzi2 << std::endl;
const char * c = memzi2.c_str();
sd = send(sock, c, sizeof(tell), NULL);
cout << "Server: ";
rcv = recv(sock,Message,sizeof(Message),NULL);
Converter = Message;
cout << Converter << endl;
std::stringstream convert1(Converter);
convert1 >> myint;
if (myint > 5000) {
myint = 1;
}
++myint;
}
closesocket(sock);
}
else cout << "Failed." << endl;
cout << "\n\n\t";
system("pause");
exit(1);
}
Thanks in advance!
Can be a simple reason, it will be using C++ CLI, i.e. common language runtime. Go to project properties and fix it up, it will not show any more.

VC11 Winsock Application Won't Shut Down

I have an interesting scenario for a winsock app that seemingly will not close. The following is enough code to fully replicate the issue:
#include "stdafx.h"
#include <WinSock2.h>
#pragma comment(lib, "ws2_32.lib")
#include <WS2tcpip.h>
#include <MSTcpIP.h>
#include <ws2ipdef.h>
#include <cstdio>
#include <iostream>
using namespace std;
int main() {
WSAData wsaStartup;
WSAStartup(MAKEWORD(2, 2), &wsaStartup);
SOCKET s = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP);
addrinfo *result;
addrinfo hint = { 0 };
hint.ai_family = AF_INET6;
int error = getaddrinfo("localhost", "45000", &hint, &result);
if (error || !result) {
cout << "Unable to resolve host. " << WSAGetLastError() << endl;
return 1;
}
error = connect(s, result->ai_addr, result->ai_addrlen);
if (error == SOCKET_ERROR) {
cout << "Unable to connect to host. " << WSAGetLastError() << endl;
} else {
cout << "Connection successful." << endl;
}
freeaddrinfo(result);
closesocket(s);
WSACleanup();
return 0;
}
I have spent numerous hours trying to track the issue down. It seems like getaddrinfo and connect both spawn an nt thread that hangs out, and prevents the app from terminating.
The only important compiler option that I changed here is: Linker->Advanced->EntryPoint where I specified "main". If I get rid of that compiler option, and change the main signature to:
int _tmain(int argc, _TCHAR* argv[])
everything seems to work fine. In my use case, I am fine having the above _tmain function, but I am wondering if anyone has any idea what magic is going on behind the scenes of the _tmain function that is making the app close.
How do I correctly set the entry point for an exe in Visual Studio?
Perhaps you need to provide the correct signature for main() to match what the runtime is expecting.

C++ winsock gives 10038 error on bind()

um, first post here, this place seems to be all over google and i can usally find my solution with having to acually ask a question my self in any site/forums; but if i sweat any more bullets over this ima hunt down whoever developed winsock and shoot them (sorry for the anger i think ive turned over every rock in every corrner of the net with no luck.... breeaatheee.... wheew)
Im new to network programming, but have been working with C++ for the last three years on a hobby level, and also been playing with AS3 recently.
Im trying to write a server (for the client with is the AS3 project im also working on) and as far as i can tell this SOCKET is perfectly fine. im not re-creating it, multi-threading with it, no re-assignment or anything. no funny bisuness. simply trying to set it all up and bind() is spitting out that nasty 10038 right in my face.
Ive looked on MSDN, and i know very well that 10038 means "attempted operation on an invalid socket"; for the life of me i cant see where its invalid.
but enough of my rambling, heres the code: (functions.h is empty, havnt got that far along yet)
//Server for Project7 - Client written in AS3 under FlashDevelop. Developed under and for the Windows Operating System Enviroment
//All connections handled under TCP/IP on port 3011
//Client is URL locked to www.cutdev.com
//Copyright Tyler Buchinski 2012 All Rights Reserved
#include <iostream>
#include "functions.h"
#define WIN32_MEAN_AND_LEAN
#include <winsock2.h>
#include <windows.h>
using namespace std;
int main()
{
const int iReqWinsockVer = 2; // Minimum winsock version required
WSADATA wsaData;
if (WSAStartup(MAKEWORD(iReqWinsockVer,0), &wsaData)==0)
{
// Check if major version is at least iReqWinsockVer
if (LOBYTE(wsaData.wVersion) >= iReqWinsockVer)
{
SOCKET SocketListen;
SocketListen = (AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(SocketListen == INVALID_SOCKET)
{
cout << "ERROR - could not creaate listening socket." << endl;
system("pause");
return 4;
}
sockaddr_in Listener, Channel1;
Listener.sin_family = AF_INET;
Listener.sin_port = htons(3011);
Listener.sin_addr.S_un.S_addr = INADDR_ANY;
int err = bind(SocketListen,(sockaddr*)(&Listener),sizeof(Listener));
if (!err == 0)
{
cout << "Listener binding failed!" << endl;
cout << err << endl;
cout << WSAGetLastError();
return 3;
}
}
else
{
// Required version not available
cout <<"Required version of Winsock not installed." << endl;
}
// Cleanup winsock
if (!WSACleanup() == 0)
{
// cleanup failed
cout << "WSACleanup Failed!!" << endl;
system("pause");
}
}
else
{
cout << "WSA Startup failed!" << endl;
}
return 0;
}
Thanks in advance for any help!
-Tyler
Error 10038 is WSAENOTSOCK:
An operation was attempted on something that is not a socket.
This error is returned if the descriptor in the s parameter is not a socket.
This happens since you omitted the call to socket() and SocketListen contains the value of the IPPROTO_TCP constant instead of a socket descriptor:
SocketListen = (AF_INET,SOCK_STREAM,IPPROTO_TCP);
should become:
SocketListen = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);