ServerSocket throws InvalidArgumentException, but docs don't specify why. Why? - c++

I'm using Poco to create a webserver. I ran into an error with the ServerSocket library. Here's the minimum code to reproduce the error.
#include <iostream>
#include "Poco/Net/ServerSocket.h"
#include "Poco/Net/StreamSocket.h"
#include "Poco/Net/SocketAddress.h"
#define PORT (unsigned short) 3000
int main()
{
Poco::Net::ServerSocket x;
x.bind(PORT);
Poco::Net::StreamSocket conn;
Poco::Net::SocketAddress clientAddr;
try {
conn = x.acceptConnection(clientAddr);
}
catch (Poco::InvalidArgumentException e) {
printf("Oh no! %s\n", e.displayText().c_str());
return 1;
}
printf("Huzzah!");
return 0;
}
I tried to look at [the docs] (https://pocoproject.org/docs/Poco.Net.ServerSocket.html#25093) to understand the error, but it doesn't even list this function as throwing this error. I've also tried the parameterless version of the function, and it still throws this exception, (which indicates to me it's not the function but a sub function throwing the error). Why? and how can I fix it, or work around it?

As WhozCraig said, the problem was not putting it in listening state. The code should be
#include <iostream>
#include "Poco/Net/ServerSocket.h"
#include "Poco/Net/StreamSocket.h"
#include "Poco/Net/SocketAddress.h"
#define PORT (unsigned short) 3000
int main()
{
Poco::Net::ServerSocket x;
x.bind(PORT);
x.listen(1); // or number of acceptable connections
Poco::Net::StreamSocket conn;
Poco::Net::SocketAddress clientAddr;
try {
conn = x.acceptConnection(clientAddr);
}
catch (const Poco::InvalidArgumentException& e) {
printf("Oh no! %s\n", e.displayText().c_str());
return 1;
}
printf("Huzzah!");
return 0;
}

Related

Listing serial ports on Windows

Header
#pragma once
#include <windows.h>
#include <iostream>
#include <stdlib.h>
#include <WinBase.h>
using namespace std;
class SerialPort {
public:
BOOL COM_exists(int port);
};
cpp
#include "stdafx.h"
#include <string.h>
#include "SerialPort.h"
using namespace std;
BOOL SerialPort::COM_exists(int port)
{
char buffer[7];
COMMCONFIG CommConfig;
DWORD size;
if (!(1 <= port && port <= 255))
{
return FALSE;
}
snprintf(buffer, sizeof buffer, "COM%d", port);
size = sizeof CommConfig;
// COM port exists if GetDefaultCommConfig returns TRUE
// or changes <size> to indicate COMMCONFIG buffer too small.
return (GetDefaultCommConfig(L"buffer", &CommConfig, &size)
|| size > sizeof CommConfig);
}
main
#include "stdafx.h"
#include <iostream>
#include "SerialPort.h"
using namespace std;
if(num==1)
{
int i;
for (i = 1; i < 256; ++i)
{
if (COM_exists(i))
{
cout <<"COM%d \n";
}
}
}
I want listing serial ports on Windows ,but I'm having a hard time.
Help me list the serial ports. error code = c3861 ,e0020
I want listing serial ports on windows.
The end of the road ,Select a serial port that can be connected to enable communication.
please help me
Main problem is here
if(num==1)
{
int i;
for (i = 1; i < 256; ++i)
{
if (COM_exists(i))
{
cout <<"COM%d \n";
}
}
}
In C++ code has to go in functions (a simplification but good enough for now) and the program starts with a special function called main. Also cout <<"COM%d \n"; is not the correct way to print a COM port, I've used the correct way in the code below. Also in the code above what is num supposed to be?
Anyway rewrite as follows and you're a little closer
int main() // start of program
{
int i;
for (i = 1; i < 256; ++i)
{
if (COM_exists(i))
{
cout << "COM " << i << "\n";
}
}
}
There are other problems such as the pointless SerialPort class. I would just remove that.
Replace
class SerialPort {
public:
BOOL COM_exists(int port);
};
with
BOOL COM_exists(int port);
and
BOOL SerialPort::COM_exists(int port)
with
BOOL COM_exists(int port)
The code looks like you are trying to learn C++ by cutting and pasting code from the internet. That is never going to work, C++ is a complex language and really needs formal study to be learned effectively. Here's a curated list of C++ books.

expected identifier before ')' token

When I tried to compile my game; and it says like
Networking/Sockets/Socket.hpp:18:81: error: expected identifier before ')' token
so if you want to see the source code I've in github here the link:
https://github.com/suky637/ServerPlusPlus
for peaple that do not want to go to github I will send you the Socket.hpp (this is the main error source) the code:
#ifndef Socket_hpp
#define Socket_hpp
#include <stdio.h>
#include <WinSock2.h>
#include <winsock.h>
#include <iostream>
namespace spp
{
class Socket {
private:
struct sockaddr_in address;
int sock;
int connection;
public:
// Constructor
Socket(int domain, int service, int protocol, int port, u_long interface_parameter);
// Virtual function to confirm to connect to the network
virtual int connect_to_network(int sock, struct sockaddr_in address) = 0;
// Function to test sockets and connection
void test_connection(int);
// Getter function
struct sockaddr_in get_address();
int get_sock();
int get_connection();
// Setter function
void set_connection(int connection_);
};
}
#endif
oh and this is the output:
// command : g++ Server.cpp -o ServerPlusPlus
In file included from Networking/Sockets/_ServerPlusPlus-sockets.hpp:6:0,
from Networking/ServerPlusPlus-Networking.hpp:6,
from ServerPlusPlus.hpp:6,
from Server.cpp:1:
Networking/Sockets/Socket.hpp:19:81: error: expected identifier before ')' token
Socket.cpp
#include "Socket.hpp"
// Default constructor
spp::Socket::Socket(int domain,
int service,
int protocol,
int port,u_long interface_parameter,
)
{
// Define address structure
address.sin_family = domain;
address.sin_port = port;
address.sin_addr.s_addr = htonl(interface_parameter);
// Establish socket
sock = socket(domain,service,protocol);
test_connection(sock);
// Establish Connection
connection = connect_to_network(sock, address);
test_connection(connect_to_network);
}
// Test Connection virtual function
void spp::Socket::test_connection(int item_to_test)
{
// Comfirm that the socket or connection has bin properly established
if (item_to_test < 0)
{
perror("Failed To Connect...");
exit(EXIT_FAILURE);
}
}
// Getter functions
struct sockaddr_in spp::Socket::get_address()
{
return address;
}
int spp::Socket::get_sock()
{
return sock;
}
int spp::Socket::get_connection()
{
return connection;
}
// Setter functions
void spp::Socket::set_connection(int connection_)
{
connection = connection_;
}
the main funtion where I compile is
#include "ServerPlusPlus.hpp"
using namespace std;
int main()
{
cout << "*--------- Starting ---------*" << endl;
cout << "* Binding Socket... ";
spp::BindingSocket bs = spp::BindingSocket(AF_INET,SOCK_STREAM,0,80,INADDR_ANY);
cout << "Complete\n* Listening Socket... ";
spp::ListeningSocket ls = spp::ListeningSocket(AF_INET, SOCK_STREAM, 0, 80, INADDR_ANY, 10);
cout << "Complete\n\n\n* Sucess!" << endl;
system("pause");
}
probably it is the file I copile and ServerPlusPlus.hpp is
#ifndef ServerPlusPlus
#define ServerPlusPlus
#include <stdio.h>
#include "Networking/ServerPlusPlus-Networking.hpp"
#endif
and ServerPlusPlus-Networking.hpp
#ifndef ServerPlusPlus_Networking_hpp
#define ServerPlusPlus_Networking_hpp
#include <stdio.h>
#include "Sockets/_ServerPlusPlus-sockets.hpp"
#endif
and ServerPlusPlus_Sockets_hpp
#ifndef ServerPlusPlus_Sockets_hpp
#define ServerPlusPlus_Sockets_hpp
#include <stdio.h>
#include "Socket.hpp"
#include "BindingSocket.hpp"
#include "ListeningSocket.hpp"
#include "ConnectingSocket.hpp"
#endif
You seem to have missed that actual answer.
interface is used as a typedef in some windows headers
see What is the "interface" keyword in MSVC?
change the name to iface or something like that

__beginthreadex was not declared in this scope

I am new to multi threading. I am trying to make a program that will listen to incoming connections, while being able to send data at the same time.
Here is the code so far. It is not finished yet, because I am stuck trying to figure out why I get this error:
__beginthreadex was not declared in this scope
Same goes for __endthreadex.
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iostream>
#include <windows.h>
#include <process.h>
#pragma comment (lib,"Ws2_32.lib")
#define PORT "27015"
#define BUFLEN 512
using namespace std;
char recvbuf[BUFLEN];
int ires;
int recvbuflen=BUFLEN;
void Thread(void* data, SOCKET *x[2]) {
listen(*x[0],128);
*x[1]=accept(*x[0],NULL,NULL);
}
int main(int argc, char **argv){
SOCKET *SOKETI[2];
HANDLE H;
string X="Ping.";
string Y;
int i;
WSADATA wsa;
i=WSAStartup(MAKEWORD(2,0),&wsa);
struct addrinfo *result=NULL, *ptr=NULL, hints;
ZeroMemory(&hints,sizeof(hints));
hints.ai_family=AF_INET;
hints.ai_socktype=SOCK_STREAM;
hints.ai_protocol=IPPROTO_TCP;
hints.ai_flags=AI_PASSIVE;
i=getaddrinfo(NULL,PORT,&hints,&result);
SOCKET LSock;
LSock=socket(result->ai_family, result->ai_socktype, result->ai_protocol);
i=bind(LSock,result->ai_addr, result->ai_addrlen);
SOCKET CSock=INVALID_SOCKET;
SOKETI[0]=&LSock;
SOKETI[1]=&CSock;
H=(HANDLE)__beginthreadx(&Thread,0,&SOKETI,0,0,0);
while(1) {
//RECIEVER
i=recv(CSock,recvbuf,recvbuflen,0);
Y.append(recvbuf, recvbuf + i);
if (i=sizeof(X)){
H=(HANDLE)__endthreadx(&Thread,0,&SOKETI,0,0,0);
CloseHandle(H);
cout<<"Recieved "<<Y<<endl;
getchar();
return 0;
}
//RECIEVER
}
}
EDIT
I realized that I misspelled the function. Other mistakes done here are another topic.

Boost property tree Bad path for nothing

I am having trouble with this library... My code works fine, the parsers/creator works too, but an err appears, I don't know why:
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/thread.hpp>
#include <string>
#include <exception>
#include <set>
#include <iostream>
#include "journal.h"
unsigned short port = 2013;
unsigned short maxConnec = 250;
unsigned short fPort() {return port;}
unsigned short fMaxConnec() {return maxConnec;}
bool load(const std::string &file)
{
using boost::property_tree::ptree;
ptree objectXML;
std::cout << "bbb";
read_xml(file, objectXML);
std::cout << "aaa";
if (file.length() == 0) // By the way, no way to do that better ? "if file doesn't exist..."
{
return 0;
}
else
{
port = objectXML.get<unsigned short>("configuration.server.port");
maxConnec = objectXML.get<unsigned short>("configuration.server.maxConnections");
return 1;
}
}
bool save(const std::string &file)
{
try
{
using boost::property_tree::ptree;
ptree objectXML;
objetXML.put("configuration.server.port", port);
objetXML.put("configuration.server.maxConnections", maxConnec);
write_xml(file, objectXML, std::locale(), boost::property_tree::xml_writer_make_settings<ptree::key_type>(' ', 4));
return 1;
}
catch (std::exception e)
{
return 0;
}
}
void generate()
{
std::string file = "configuration.xml";
try{
if (!load(fichier))
{
save(file);
}
}
catch (std::exception &e)
{
load(file);
}
}
Get a bad path, I totally don't know why because when I try to read data I can and it gets the data in configuration.xml even if I change it...
The ptree_bad_path exception is raised from the throwing version of get and signals that "configuration.server.port" or "configuration.server.maxConnections" path to the XML element doesn't exist.
The error isn't related to the configuration.xml file path.
So you should check the element name or, for optional elements, use the default-value / optional-value version of get.

How to get domain ip address using domain name in C++?

i am using visual c++,
I want to get a domain ip address from domain name..
how do i get it..
i already tried gethostbyname function...
here my code...
HOSTENT* remoteHost;
IN_ADDR addr;
hostName = "domainname.com";
printf("Calling gethostbyname with %s\n", hostName);
remoteHost =gethostbyname(hostName);
memcpy(&addr.S_un.S_addr, remoteHost->h_addr, remoteHost->h_length);
printf("The IP address is: %s\n", inet_ntoa(addr));
But i get a wrong ip address.
Here's complete source code to a little utility I find handy at times (I've named it "resolve"). All it does is resolve a domain name to a numeric IP (v4) address, and print it out. As-is, it's for Windows -- for Linux (or similar) you'd just need to get rid of the use_WSA class (and object thereof).
#include <windows.h>
#include <winsock.h>
#include <iostream>
#include <iterator>
#include <exception>
#include <algorithm>
#include <iomanip>
#include "infix_iterator.h"
class use_WSA {
WSADATA d;
WORD ver;
public:
use_WSA() : ver(MAKEWORD(1,1)) {
if ((WSAStartup(ver, &d)!=0) || (ver != d.wVersion))
throw(std::runtime_error("Error starting Winsock"));
}
~use_WSA() { WSACleanup(); }
};
int main(int argc, char **argv) {
if ( argc < 2 ) {
std::cerr << "Usage: resolve <host-name>";
return EXIT_FAILURE;
}
try {
use_WSA x;
hostent *h = gethostbyname(argv[1]);
unsigned char *addr = reinterpret_cast<unsigned char *>(h->h_addr_list[0]);
std::copy(addr, addr+4, infix_ostream_iterator<unsigned int>(std::cout, "."));
}
catch (std::exception const &exc) {
std::cerr << exc.what() << "\n";
return EXIT_FAILURE;
}
return 0;
}
This also uses the infix_ostream_iterator I've posted previously.