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.
Related
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
I am trying to understand the nature of getsockopt(int s, int level, int optname, void *optval, socklen_t *optlen).
I am trying to see the initial status of SO_DEBUG and I am referring to this link https://www.mkssoftware.com/docs/man3/getsockopt.3.asp , and I am not sure if I am doing this the correct way because I am getting random values.
//***********************************************Libraries****************************************************************
#include <iostream>
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>
#include <errno.h>
using namespace std;
//************************************************************************************************************************
int main()
{
int * optval;
int optionDebug = 0;
socklen_t optlen;
int sockFD;
sockFD = socket(AF_INET, SOCK_STREAM ,0);
optlen =sizeof(optval);
int udpFD;
udpFD = socket(AF_INET, SOCK_DGRAM,0);
optionDebug = getsockopt(sockFD, SOL_SOCKET, SO_DEBUG, optval, &optlen) ;
cout<<"My value "<< *optval<<endl;
return 0;
}
To retrieve the value for optval you need to pass the address of a valid variable (not an uninitialized pointer):
ExpectedOptType optval;
// ^^^^^^^^^^^^^^^ Put whatever type (probably a enum) is expected for
// the specific option
optionDebug = getsockopt(sockFD, SOL_SOCKET, SO_DEBUG, &optval, &optlen);
// ^
Read more details about how it works here: getsockopt(2).
Linux socket programming problem.
I'm working on a multithreaded server which can accept the connect from several client. My problem is that when I run the following code, it creates 10 threads and then exit without waiting for the connect from client. Could anyone tell me what's wrong with my code? Thanks a lot.
// include the library for socket programming
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
// include other useful library
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <string>
#include <pthread.h>
#include <fstream>
#include <time.h>
using namespace std;
static int ListenSoc;
#define LISTENPORT 6000
#define THREADNUM 10
void *AcceptAndService(void *){
int ClientSoc;
socklen_t CliLen;
struct sockaddr_in CliAdd;
CliLen=sizeof(CliAdd);
memset((char *)&CliAdd,0,sizeof(CliAdd));
//accept the connect from the client to do the login
if(ClientSoc=accept(ListenSoc,(struct sockaddr*)&CliAdd,&CliLen)){
cout<<"connection from "<<inet_ntoa(CliAdd.sin_addr)<<" has found\n";
}
pthread_exit(NULL);
}
int main(){
//create the thread
pthread_t thread[THREADNUM];
//Doing the listen
struct sockaddr_in SerAdd;
ListenSoc=socket(AF_INET,SOCK_STREAM,0);
// set the address
memset((char *)&SerAdd,0,sizeof(SerAdd));
SerAdd.sin_port=htons(LISTENPORT);
SerAdd.sin_family=AF_INET;
SerAdd.sin_addr.s_addr = INADDR_ANY;
//bind
if(bind(ListenSoc,(struct sockaddr*)&SerAdd,sizeof(SerAdd))==-1)
cout<<"Error in bind";
else
cout<<"Bind success";
//listen
if(listen(ListenSoc,5)==-1)
cout<<"Error in listen";
else
cout<<"\n\t the register server is waiting for the connection...\n"<<endl;
//Accept the connect from client
int i;
for(i=0;i<THREADNUM;i++){
cout<<"Accept thread "<<i<<" is being created"<<endl;
pthread_create(&thread[i], NULL, AcceptAndService, NULL);
}
return 0;
}
You have to call pthread_join after the for loop, to wait for the threads ending:
int i;
for(i=0;i<THREADNUM;i++){
cout<<"Accept thread "<<i<<" is being created"<<endl;
pthread_create(&thread[i], NULL, AcceptAndService, NULL);
}
for(i=0;i<THREADNUM;i++){
pthread_join(thread[i], NULL);
}
I am trying to write a program that has two separate process that talk via named pipes. The client which sends a message to a server, and the server which needs to broadcast that message to all clients attached to it. So far, I can get a connection between the two, but I cannot get more than one message to work no matter what I have tried. Below is the code I have written that will allow a connection and transmission of a single message.
server.cpp:
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#define FIFO_FILE_1 "/tmp/client_to_server_fifo"
#define FIFO_FILE_2 "/tmp/server_to_client_fifo"
int main()
{
int client_to_server;
int server_to_client;
char buf[BUFSIZ];
/* create the FIFO (named pipe) */
mkfifo(FIFO_FILE_1, 0666);
mkfifo(FIFO_FILE_2, 0666);
printf("Server ON.\n");
while (1)
{
/* open, read, and display the message from the FIFO */
client_to_server = open(FIFO_FILE_1, O_RDONLY);
server_to_client = open(FIFO_FILE_2, O_WRONLY);
read(client_to_server, buf, BUFSIZ);
if (strcmp("exit",buf)==0)
{
printf("Server OFF.\n");
break;
}
else if (strcmp("",buf)!=0)
{
printf("Received: %s\n", buf);
printf("Sending back...\n");
write(server_to_client,buf,BUFSIZ);
}
/* clean buf from any data */
memset(buf, 0, sizeof(buf));
close(client_to_server);
close(server_to_client);
}
close(client_to_server);
close(server_to_client);
unlink(FIFO_FILE_1);
unlink(FIFO_FILE_2);
return 0;
}
client.cpp:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <wait.h>
#include <string.h>
#define FIFO_FILE_1 "/tmp/client_to_server_fifo"
#define FIFO_FILE_2 "/tmp/server_to_client_fifo"
int main()
{
system("clear");
int client_to_server;
int server_to_client;
char str[140];
printf("Input message to server: ");
scanf("%139[^\r\n]", str);
/* write str to the FIFO */
client_to_server = open(FIFO_FILE_1, O_WRONLY);
server_to_client = open(FIFO_FILE_2, O_RDONLY);
if(write(client_to_server, str, sizeof(str)) < 0){
perror("Write:");//print error
exit(-1);
}
if(read(server_to_client,str,sizeof(str)) < 0){
perror("Read:"); //error check
exit(-1);
}
printf("\n...received from the server: %s\n\n\n",str);
close(client_to_server);
close(server_to_client);
/* remove the FIFO */
return 0;
}
close(client_to_server);
close(server_to_client);
Remove these lines from while loop because when server has done its work for the first time it will close the pipe and you cant be able to proceed further in pipes.
this program can detect http flow and etc....
but it ignores XMPP flow ; i don't know why ?
(I guess this is a port problem , but i don't know where i should fix it )
Below are the relevant sections from main.cpp :
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdio.h>
#include "nids.h"
#include <cstdlib>
#include <unistd.h>
#define int_ntoa(x) inet_ntoa(*((struct in_addr *)&x))
// struct tuple4 contains addresses and port numbers of the TCP connections
// the following auxiliary function produces a string looking like
// 10.0.0.1,1024,10.0.0.2,23
char *
adres (struct tuple4 addr)
{
static char buf[256];
strcpy (buf, int_ntoa (addr.saddr));
sprintf (buf + strlen (buf), ",%i,", addr.source);
strcat (buf, int_ntoa (addr.daddr));
sprintf (buf + strlen (buf), ",%i", addr.dest);
return buf;
}
void
tcp_callback (struct tcp_stream *a_tcp, void ** this_time_not_needed)
{
printf("packet captured !\n");
}
int
main ()
{
// here we can alter libnids params, for instance:
// nids_params.n_hosts=256;
struct nids_chksum_ctl nochksumchk;
nochksumchk.netaddr = 0;
nochksumchk.mask = 0;
nochksumchk.action = NIDS_DONT_CHKSUM;
//char fileName[] = "/home/test.pcap";
//nids_params.filename =fileName;
nids_register_chksum_ctl(&nochksumchk, 1);
char myDevice [] = "eth0";
nids_params.device =myDevice;
if (!nids_init ())
{
fprintf(stderr,"%s\n",nids_errbuf);
exit(1);
}
nids_register_tcp ( (void*)tcp_callback);
nids_run ();
return 0;
}
My pcap file has some problem about syncing in tcp connection .
So above snippet code of libnids is correct !