C++ INET noob, what am I doing wrong? - c++

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <string.h>
#include <cstdio>
using namespace std;
int main(int argc, char *argv[])
{
int port, n,sockfd;
struct sockaddr_in srv_addr;
struct hostent *serv;
char buffer[256];
if(argc<3)
{
cout <<"\n ussage: host port\nexiting\n";
return 0;
}
port=atoi(argv[2]);
sockfd=socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
cout <<"\nsocket creation on"<<port<<" failed\nexiting\ncheck to see if port is in use";
return 0;
}
serv = gethostbyname(argv[1]);
if (serv=NULL)
{
cout <<"\n"<<serv<<" is not a valid host name\nexiting";
return 0;
}
bzero((char *) &srv_addr, sizeof(srv_addr));
srv_addr.sin_family=AF_INET;
bcopy((char *) serv->h_addr,
(char *) &srv_addr.sin_addr.s_addr,
serv->h_length);
srv_addr.sin_port=htons(port);
if (connect(sockfd,&srv_addr,
sizeof (srv_addr))<0)
{
cout <<" \nconnection failed\n";
}
cout <<"\nType message\n";
bzero(buffer, 256);
cin.getline(buffer,256);
n=write(sockfd,buffer,strlen(buffer));
if (n>0)
{
cout <<"\nsocket write error\nexiting\n";
}
n=read(sockfd,buffer,255);
if (n>0)
{
cout <<"\nsocket read error\nexiting\n";
}
cout <<buffer;
return 0;
}
When compiled, I get this error:
fg.c: In function ‘int main(int, char**)’:
fg.c:53:33: error: cannot convert ‘sockaddr_in*’ to ‘const sockaddr*’ for argument ‘2’ to ‘int connect(int, const sockaddr*, socklen_t)’
I cant figure it out. I am a noob to programming. Any help is grateful.

You need explicit cast. Replace
connect(sockfd,&srv_addr, sizeof (srv_addr))
with
connect(sockfd,(sockaddr*)&srv_addr, sizeof (srv_addr))

Related

How to create or manage Libuv TCP server in a c++ fuction?

I am trying to create a TCP server in a function int create_server(int port_number, char ip_addr_string[IPV4_ADDR_SIZE]) which is called in main.
When I run the c++ code given below: Assertion failed: (w->fd >= 0), function uv__io_poll, file kqueue.c, line 149.
#include <iostream>
#include <vector>
#include <algorithm>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <future>
#include <sys/types.h>
#include <uv.h>
#define IPV4_ADDR_SIZE 15
uv_loop_t* loop;
struct sockaddr_in addr;
std::map <int, uv_tcp_t * > pool;
int create_tunnel(int port_number, char ip_addr_string[IPV4_ADDR_SIZE]){
uv_tcp_t global_server;
uv_tcp_init(loop, &global_server);
uv_ip4_addr("0.0.0.0", port_number, &addr);
uv_tcp_bind(&global_server, (const struct sockaddr *)&addr, 0);
int r = uv_listen((uv_stream_t *)&global_server, 128, NULL);
if(r){
fprintf(stderr, "Listen error: %s \n", uv_strerror(r));
}
else{
fprintf(stdout, "Listening on: %d \n", port_number);
}
pool[rand()] = &global_server;
return r;
}
int main(int argc, const char *argv[]){
int status = 1;
loop = uv_default_loop();
uv_loop_init(loop);
loop->data = &pool;
status = create_tunnel(7011, (char*)"0.0.0.0");
std::cout<< "status: " << status << std::endl;
uv_run(loop, UV_RUN_DEFAULT);
return 0;
I think this error is because the servers created are not tracked by the event_loop when the create_server function ends, but I am not sure.
Any help, please?

C++ - msgsnd & msgrcv communication between 2 different programs

I have two programs and I want them to communicate together by msgrcv() && msgsnd(). I so have a master program which init the message queue and start the 2 others programs:
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string>
#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <stdio.h>
int main() {
int qid = msgget(ftok(".",'u'), 0);
char* params[3];
params[1] = (char *)malloc(sizeof(char) * 9);
sprintf(params[1], "%d", qid);
params[2] = NULL;
printf("qid = %d and qid(str) = %s", qid, params[1]);
// return (0);
//spawning two child processes
pid_t cpid = fork();
if (cpid == 0) {
params[0] = (char*)"./sender";
execv(params[0], params);
exit(0);
}
cpid = fork();
if (cpid == 0) {
params[0] = (char*)"./receiver";
execv(params[0], params);
exit(0);
}
while (wait(NULL) != -1); // waiting for both children to terminate
msgctl(qid, IPC_RMID, NULL);
std::cout << "parent proc: " << getpid()
<< " now exits" << std::endl;
exit(0);
}
I also prepare the parameters and start the both following programs:
sender
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
int main(int ac, char **av) {
if (ac != 2)
return (-1);
// create my msgQ with key value from ftok()
// int qid = msgget(IPC_PRIVATE, IPC_EXCL|IPC_CREAT|0600);
int qid = atoi(av[1]);
// declare my message buffer
struct buf {
long mtype; // required
char greeting[50]; // mesg content
};
buf msg;
int size = sizeof(msg)-sizeof(long);
std::cout << "Welcome in the prog assignment 2! Type [exit] to stop the program." << std::endl;
bool exit = false;
while (!exit)
{
std::cout << getpid() << ": ";
std::cin.getline(msg.greeting, 50, '\n');
std::cout << msg.greeting << std::endl;
msg.mtype = 114; // only reading mesg with type mtype = 114
if (strcmp(msg.greeting, "exit") == 0)
exit = true;
msgsnd(qid, (struct msgbuf *)&msg, size, 0);
}
}
receiver
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <stdio.h>
int main(int ac, char **av) {
int i = 0;
while (i < ac)
printf("AV: %s\n", av[i++]);
if (ac != 2)
return (-1);
// int qid = msgget(IPC_PRIVATE, IPC_EXCL|IPC_CREAT|0600);
int qid = atoi(av[1]);
// declare my message buffer
struct buf {
long mtype;
char greeting[50];
};
buf msg;
int size = sizeof(msg)-sizeof(long);
bool exit = false;
while (!exit)
{
msgrcv(qid, (struct msgbuf *)&msg, size, 114, 0);
if (strcmp(msg.greeting, "exit") == 0)
exit = true;
std::cout << getpid() << msg.greeting << std::endl;
}
std::cout << "get out" << std::endl;
}
It doesn't work and I'm not sure to understand why because, I'm creating the message queue, passing it as parameter, then I put it back as int and then use it. However, it just gives me an infinite loop of weird display, why?
ANy help is welcome.. Thank !

Error on call to shmat

Try to do something with shared memory by turning a chunk of user buffer into a shared memory, but the shmat() keep failing.
# ./a.out
shmid=89260087 0x7fbab055c000
shmat failed: : Invalid argument
Here is the source code. Wonder what's the reason. Thanks.
#include <arpa/inet.h>
#include <string.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/shm.h>
#include <malloc.h>
char *output;
int n;
int main (int argc, char *argv[]) {
void *p = NULL;
int i;
double startTS;
double tmp;
output = (char*) valloc(0x1000000);
sprintf(output, "hi you!!");
unsigned int size = 0x1000000;
int shmid = shmget(12348, 0x1000000, IPC_CREAT); //SHM_RDONLY);
printf("shmid=%d %p\n", shmid, &output[0]);
char *bigBuf = (char*)shmat(shmid, &output[0], 0);
if (bigBuf == (void*)-1) {
perror("shmat failed: "); exit(-1);
}
bigBuf[0] = 'x';
printf("%p enter:\n", bigBuf);
scanf("%d\n", &i);
return 0;
}

Bluez libraries cause a lot of problems

I'm trying to compile a C++ project on raspberry pi B+ in codeblocks. Code is taken from here
#include <iostream>
#include <cstdint>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/hci.h>
#include <bluetooth/hci_lib.h>
using namespace std;
int main()
{
//cout << "Hello world!" << endl;
inquiry_info *li = NULL;
int max_rsp, num_rsp;
int dev_id, sock, len, flags;
int i;
char addr[19] = {0};
char name[248] = {0};
dev_id = hci_get_route(NULL);
sock = hci_open_dev(dev_id);
if(dev_id < 0||sock < 0)
{
perror("opening socket");
exit(1);
}
len=8;
max_rsp = 255;
flags = IREQ_CACHE_FLUSH;
li = (inquiry_info*)malloc(max_rsp * sizeof(inquiry_info));
num_rsp = hci_inquiry(dev_id, len, max_rsp, NULL, &li, flags);
if(num_rsp) perror("hci_inquiry");
for(i = 0; i < num_rsp; i++)
{
ba2str(&(li+i)->bdaddr, addr);
memset(name, 0, sizeof(name));
if(hci_read_remote_name(sock, &(li+i)->bdaddr, sizeof(name), name, 0) < 0) strcpy(name, "[unknown]");
printf("%s %s\n", addr, name);
}
free(li);
close(sock);
return 0;
}
GCC 4.6 with [std=c++0x] flag gives me the next errors:
/home/pi/bluez-5.11/lib/bluetooth/hci.h|315|error: ‘uint8_t’ does not name a type|
/home/pi/bluez-5.11/lib/bluetooth/hci.h|316|error: ‘uint8_t’ does not name a type|
/home/pi/bluez-5.11/lib/bluetooth/hci.h|317|error: ‘uint8_t’ does not name a type|
/home/pi/bluez-5.11/lib/bluetooth/hci.h|322|error: ‘uint8_t’ does not name a type|
/home/pi/bluez-5.11/lib/bluetooth/hci.h|323|error: ‘bdaddr_t’ does not name a type|
/home/pi/bluez-5.11/lib/bluetooth/hci.h|331|error: ‘uint16_t’ does not name a type|
/home/pi/bluez-5.11/lib/bluetooth/hci.h|332|error: ‘uint16_t’ does not name a type|
As you can see I have <cstdint> and using namespace std lines. What am i doing wrong?

Boost, creating a thread that's creating a socket reader - Getting a compile error

I'm writing code for a gateway (aka router), using boost, C++, Codeblocks on a Linux device running Debian 7.1. I'm stuck with an annoying boost bind error and I simply cannot figure out what the problem is. I have been able to print out the MAC Header before I started creating threads
Here's a my code:
#include <errno.h>
#include <sys/ioctl.h>
#include <boost/thread.hpp>
#include <boost/function.hpp>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <linux/if_packet.h>
#include <linux/if_ether.h>
#include <linux/if_arp.h>
#include <iostream>
#include <features.h>
#include <stdlib.h>
using namespace std;
int CreateRawSocket(int protocol_to_sniff)
{
int s;
if((s = socket(AF_PACKET, SOCK_RAW, htons(protocol_to_sniff))) == -1)
{
perror("Error creating raw socket");
exit(-1);
}
return s;
}
int BindRawSocketToInterface(char *device, int raw, int protocol)
{
struct sockaddr_ll sll;
struct ifreq ifr;
bzero(&sll, sizeof(sll));
bzero(&ifr, sizeof(ifr));
strncpy((char *)ifr.ifr_name, device, IFNAMSIZ);
if((ioctl(raw, SIOCGIFINDEX, &ifr)) == -1)
{
printf("Error getting interface index!\n");
exit(-1);
}
sll.sll_family = AF_PACKET;
sll.sll_ifindex = ifr.ifr_ifindex;
sll.sll_protocol = htons(protocol);
if((bind(raw, (struct sockaddr *)&sll, sizeof(sll))) == -1)
{
perror("Error binding raw socket to interface\n");
exit(-1);
}
return 1;
}
int rawpacket_recv(int s, unsigned char *packet, int length)
{
int to_recv = 0;
to_recv = read(s, packet, length);
if(to_recv == -1)
{
perror("Error receiving packet");
exit(-1);
}
return to_recv;
}
int PrintPacketMACHdr(unsigned char *eth_packet)
{
unsigned char *ethhead;
int j;
ethhead = eth_packet;
printf("---Start of Ethernet header---");
printf("\nDestination address:\n");
for(j = 0; j < 6; j++)
{
printf("%02x:", *(ethhead+j)); //destination address (0 to 6 bit)
}
printf("\nSource address:\n");
for(j = 6; j < 12; j++)
{
printf("%02x:", *(ethhead+j)); //source address
}
printf("\nEther protocol number:\n");
for(j = 12; j < 14; j++)
{
printf("%02x", *(ethhead+j)); //protocol number
}
printf("\n---End of Ethernet header---\n");
if(*(ethhead + 12) == 8 && *(ethhead + 13) == 0)
{
return 1; //IP packet
}
if(*(ethhead + 12) == 8 && *(ethhead + 13) == 6)
{
return 2; //ARP packet
}
return 0;
}
int CreateAndBindSocket(int protocol_to_sniff, int *socket, char *interface)
{
int ethSocket = *socket; //eth1recv;
ethSocket = CreateRawSocket(protocol_to_sniff);
BindRawSocketToInterface(interface, ethSocket, ETH_P_ALL);
return ethSocket;
}
void RecvThread(int *socket) //thread function for receiving packets
{
int counter;
unsigned char *eth_buffer;
int eth_receiver;
int eth_socket = *socket
eth_buffer = (unsigned char *)malloc(ETH_P_ALL);
eth_receiver = rawpacket_recv(eth_socket, eth_buffer, ETH_P_ALL);
for(;;)
{
cout << "thread iteration " << ++counter << " Press Enter to stop" << endl;
try
{
//Sleep and check for interrupt();
//boost::this_thread::sleep(boost::posix_time::milliseconds(500));
usleep(50000);
PrintPacketMACHdr(eth_buffer);
}
catch(boost::thread_interrupted&)
{
cout << "Thread is stopped" << endl;
return;
}
}
}
int main(int argc, char **argv)
{
int eth0socket, eth1socket;
char eth0[] = "eth0";
char eth1[] = "eth1";
eth0socket = CreateAndBindSocket(ETH_P_ALL, &eth0socket, eth0);
eth1socket = CreateAndBindSocket(ETH_P_ALL, &eth1socket, eth1);
boost::thread eth0recvthread(RecvThread, &eth0socket); //instantiate thread in main
char ch;
cin.get(ch);
eth0recvthread.interrupt();
eth0recvthread.join();
return 0;
}
Right now I'm trying to create a thread that listens on one of the sockets and (for now) prints the MAC Header of the Ethernet frame. Later I will have to save the packet in some sort of array and then make another thread that handles the packets in this array. But as the headline says, I'm getting a boost error:
/home/thomas/Workspace/minisniffer/main.cpp||In function ‘void RecvThread(int)’:|
/home/thomas/Workspace/minisniffer/main.cpp|181|warning: variable ‘eth_receiver’ set but not used [-Wunused-but-set-variable]|
../../../../usr/local/boost_1_54_0/boost/bind/bind_template.hpp|20| required from ‘boost::_bi::bind_t<R, F, L>::result_type boost::_bi::bind_t<R, F, L>::operator()() [with R = void; F = void (*)(int); L = boost::_bi::list1<boost::_bi::value<int*> >; boost::_bi::bind_t<R, F, L>::result_type = void]’|
../../../../usr/local/boost_1_54_0/boost/thread/detail/thread.hpp|117| required from ‘void boost::detail::thread_data<F>::run() [with F = boost::_bi::bind_t<void, void (*)(int), boost::_bi::list1<boost::_bi::value<int*> > >]’|
/home/thomas/Workspace/minisniffer/main.cpp|306| required from here|
../../../../usr/local/boost_1_54_0/boost/bind/bind.hpp|253|error: invalid conversion from ‘int*’ to ‘int’ [-fpermissive]|
../../../../usr/local/boost_1_54_0/boost/system/error_code.hpp|222|warning: ‘boost::system::posix_category’ defined but not used [-Wunused-variable]|
../../../../usr/local/boost_1_54_0/boost/system/error_code.hpp|223|warning: ‘boost::system::errno_ecat’ defined but not used [-Wunused-variable]|
../../../../usr/local/boost_1_54_0/boost/system/error_code.hpp|224|warning: ‘boost::system::native_ecat’ defined but not used [-Wunused-variable]|
||=== Build finished: 4 errors, 4 warnings ===|
Tbh I have no idea what's failing, but then again I'm pretty new to C++ and Boost.
The creating and binding of sockets works just fine as they have been tested already, but the thread function RecvThread() is the one that fails me.
If someone has some idea to what I'm doing wrong (could easily be a pointer (*) or address (&) that is messing everything up) I would be so thankful!!
Thanks in advance!