error: 'InetPton' was not declared in this scope while compiling c++ - c++

I'm new to c++ and when I try to compile the code, I get the following:
In file included from C:\Users\Toqa\Documents\Keylogger\main.cpp:10:
C:\Users\Toqa\Documents\Keylogger\SendData.h: In constructor
'Data::Data()': C:\Users\Toqa\Documents\Keylogger\SendData.h:34:13:
error: 'InetPton' was not declared in this scope InetPton(AF_INET,
"172.0.0.1", &addr.sin_addr.s_addr); ^~~~~~~~
C:\Users\Toqa\Documents\Keylogger\SendData.h:34:13: note: suggested
alternative: 'inet_ntoa' InetPton(AF_INET, "172.0.0.1",
&addr.sin_addr.s_addr); ^~~~~~~~ inet_ntoa
This is my code:
#ifndef SENDDATA_H
#define SENDDATA_H
#include <winsock2.h>
#include <ws2tcpip.h>
#include "IO.h"
#include<iostream>
#include<fstream>
#include<stdio.h>
#include <unistd.h>
#include <stdlib.h>
class Data{
std::fstream file;
int general_socket_descriptor;
struct sockaddr_in address;
int address_length;
WSADATA wsa_data;
SOCKADDR_IN addr;
int server;
public:
Data(){
create_socket();
InetPton(AF_INET, "172.0.0.1", &addr.sin_addr.s_addr);
addr.sin_family = AF_INET;
addr.sin_port = htons(55555);
create_connection();
std::string path = IO::GetOurPath(true);
file.open(path + "test.txt", std::ios::in | std::ios::binary);
if(file.is_open()){
std::cout<<"[LOG] : File Ready...\n";
}
else{
std::cout<<"[ERROR] : File creation failed, Exiting.\n";
}
}
void create_socket(){
WSAStartup(MAKEWORD(2, 0), &wsa_data);
if (server = socket(AF_INET, SOCK_STREAM, 0)) {
std::cout<<"[LOG] : Socket Created Successfully.\n";
}
else{
perror("[ERROR] : Socket failed.\n");
}
}
void create_connection(){
if (connect(server, reinterpret_cast<SOCKADDR *>(&addr), sizeof(addr)) < 0) {
perror("[ERROR] : connection attempt failed.\n");
}
std::cout<<"[LOG] : Connection Successfull.\n";
}
void transmit_file(){
std::string contents((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
std::cout<<"[LOG] : Transmission Data Size "<<contents.length()<<" Bytes.\n";
std::cout<<"[LOG] : Sending...\n";
int bytes_sent = send(server , contents.c_str() , contents.length() , 0 );
std::cout<<"data: "<<contents.c_str()<<"\n end \n";
std::cout<<"[LOG] : Transmitted Data Size "<<bytes_sent<<" Bytes.\n";
std::cout<<"[LOG] : File Transfer Complete.\n";
}
};
#endif // SENDDATA_H
I'm using code blocks IDE on windows and this is the command of compiling:
g++.exe -o bin\Debug\Test.exe obj\Debug\main.o -mwindows -lws2_32
The version is:
g++ (x86_64-posix-seh-rev0, Built by MinGW-W64 project) 8.1.0
After researching the error, most of the solutions were ensuring to link it with ws2_32. However, I'm using it and I still get the same error.

Related

Encode png to RGBA(8888) in ImageMagick (c++)

I'm trying to convert a png to RGBA buffer and send it via tcp sockets, I've made a socket but i'm a begginer at image manipulation, how should I convert it to RGBA buffer and send it via sockets? I'm trying to use ImageMagick because it has a c++ api and i need to make this project work on c++
Socket Server:
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <Magick++.h>
using namespace std;
class Server_socket{
fstream file;
int PORT;
int general_socket_descriptor;
int new_socket_descriptor;
struct sockaddr_in address;
int address_length;
public:
Server_socket(){
create_socket();
PORT = 8050;
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons( PORT );
address_length = sizeof(address);
bind_socket();
set_listen_set();
accept_connection();
file.open(".//Data//Server//image.png", ios::in | ios::binary);
if(file.is_open()){
cout<<"[LOG] : File is ready to Transmit.\n";
}
else{
cout<<"[ERROR] : File loading failed, Exititng.\n";
exit(EXIT_FAILURE);
}
}
void create_socket(){
if ((general_socket_descriptor = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("[ERROR] : Socket failed");
exit(EXIT_FAILURE);
}
cout<<"[LOG] : Socket Created Successfully.\n";
}
void bind_socket(){
if (bind(general_socket_descriptor, (struct sockaddr *)&address, sizeof(address))<0) {
perror("[ERROR] : Bind failed");
exit(EXIT_FAILURE);
}
cout<<"[LOG] : Bind Successful.\n";
}
void set_listen_set(){
if (listen(general_socket_descriptor, 3) < 0) {
perror("[ERROR] : Listen");
exit(EXIT_FAILURE);
}
cout<<"[LOG] : Socket in Listen State (Max Connection Queue: 3)\n";
}
void accept_connection(){
if ((new_socket_descriptor = accept(general_socket_descriptor, (struct sockaddr *)&address, (socklen_t*)&address_length))<0) {
perror("[ERROR] : Accept");
exit(EXIT_FAILURE);
}
cout<<"[LOG] : Connected to Client.\n";
}
void transmit_file(){
std::string contents((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
cout<<"[LOG] : Transmission Data Size "<<contents.length()<<" Bytes.\n";
cout<<"[LOG] : Sending...\n";
int bytes_sent = send(new_socket_descriptor , contents.c_str() , contents.length() , 0 );
cout<<"[LOG] : Transmitted Data Size "<<bytes_sent<<" Bytes.\n";
cout<<"[LOG] : File Transfer Complete.\n";
}
};
int main(){
Server_socket S;
S.transmit_file();
return 0;
}
EDIT:
I found a method from this gentleman, i'm currently saving as txt to see what i got, can anyone confirm me if the data is correct (converted from png to rgba), and if it is, how can i send to my client socket as a buffer?
InitializeMagick(NULL);
Magick::Image image;
image.read("/home/img.png");
size_t image_size = image.columns() * image.rows() * 4;
uint8_t * pixels = new uint8_t[image_size];
image.write(0, 0, image.columns(), image.rows(), "RGBA", ::Magick::CharPixel, pixels);
image.write("/home/img.txt");

C++ socket error C1083: Cannot open include file: 'unistd.h': No such file or directory [duplicate]

This question already has answers here:
Cannot open include file: 'unistd.h': No such file or directory
(3 answers)
Closed 4 years ago.
I'm following this tutorial https://www.geeksforgeeks.org/socket-programming-cc/. I'm trying to practice Socket Programming in C/C++. Can someone tell me why I'm recieving this error and how to fix it?
error C1083: Cannot open include file: 'unistd.h': No such file or directory
thanks in advance
#include<iostream>
#include<string>
#include <unistd.h>
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string.h>
#define PORT 8080
using namespace std;
int main()
{
int server_fd, new_socket, valread;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[1024] = { 0 };
char *hello = "Hello from server";
// Creating socket file descriptor
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0)
{
perror("socket failed");
exit(EXIT_FAILURE);
}
// Forcefully attaching socket to the port 8080
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT,
&opt, sizeof(opt)))
{
perror("setsockopt");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
// Forcefully attaching socket to the port 8080
if (bind(server_fd, (struct sockaddr *)&address,
sizeof(address))<0)
{
perror("bind failed");
exit(EXIT_FAILURE);
}
if (listen(server_fd, 3) < 0)
{
perror("listen");
exit(EXIT_FAILURE);
}
if ((new_socket = accept(server_fd, (struct sockaddr *)&address,
(socklen_t*)&addrlen))<0)
{
perror("accept");
exit(EXIT_FAILURE);
}
valread = read(new_socket, buffer, 1024);
printf("%s\n", buffer);
send(new_socket, hello, strlen(hello), 0);
printf("Hello message sent\n");
return 0;
return 0;
}
unistd.h is for a unix system. I assume you're working with windows?

Using g++ to compile and link program with header cpp files in subfolder

Very new to this C++ thing and have been trying all night to compile a basic program with header files in a subfolder - I must be something so stupid but easily fixed. Maybe my lack of understanding around namespaces - or how headers are included???
Hopefully someone can help me out
All the examples seem to say I can compile / link on one line or in separate steps - the separate steps seems to give me the least number of errors
I can get the cpp files to compile and create .o files but can't get the output file to be created.
Final try: g++ ProcessCAP.o ./network/SocketClient.o -o ProcessCAP
Error message:
./network/SocketClient.o:(.rodata+0xc0): undefined reference to 'CAP::SocketClient::send(std::string)'
collect2: error: ld returned 1 exit status
Main Program:
#include <iostream>
#include <signal.h>
#include "network/SocketClient.h"
using namespace std;
using namespace CAP;
//int argc, char *argv[]
int main(void){
cout << "Starting CAP Processor Example" << "\n";
SocketClient sc("streaming1.my-url.com", 8080);
sc.connectToServer();
string rec = sc.receive(4096);
while (rec.length() > 0) {
cout << "Received [" << rec << "] \n";
string rec = sc.receive(4096);
}
sc.disconnectFromServer();
cout << "End of CAP Processor Example" << "\n";
}
Files in the "network" subfolder:
SocketClient.cpp
#include "SocketClient.h"
#include <stdio.h>
#include <string.h>
#include <unistd.h>
using namespace std;
namespace CAP {
SocketClient::SocketClient(std::string serverName, int portNumber) {
this->socketfd = -1;
this->server = NULL;
this->serverName = serverName;
this->portNumber = portNumber;
this->isConnected = false;
}
int SocketClient::connectToServer(){
socketfd = socket(AF_INET, SOCK_STREAM, 0);
if (socketfd < 0){
perror("Socket Client: error opening socket.\n");
return 1;
}
server = gethostbyname(serverName.data());
if (server == NULL) {
perror("Socket Client: error - no such host.\n");
return 1;
}
bzero((char *) &serverAddress, sizeof(serverAddress));
serverAddress.sin_family = AF_INET;
bcopy((char *)server->h_addr,(char *)&serverAddress.sin_addr.s_addr, server->h_length);
serverAddress.sin_port = htons(portNumber);
if (connect(socketfd, (struct sockaddr *) &serverAddress, sizeof(serverAddress)) < 0){
perror("Socket Client: error connecting to the server.\n");
return 1;
}
this->isConnected = true;
return 0;
}
string SocketClient::receive(int size=4096){
char readBuffer[size];
int n = read(this->socketfd, readBuffer, sizeof(readBuffer));
if (n < 0){
perror("Socket Client: error reading from socket");
}
return string(readBuffer);
}
int SocketClient::disconnectFromServer(){
this->isConnected = false;
close(this->socketfd);
return 0;
}
SocketClient::~SocketClient() {
if (this->isConnected == true){
disconnectFromServer();
}
}
} /* namespace CAP */
SocketClient.h (also in network subfolder)
#ifndef SOCKETCLIENT_H_
#define SOCKETCLIENT_H_
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string>
namespace CAP {
class SocketClient {
private:
int socketfd;
struct sockaddr_in serverAddress;
struct hostent *server;
std::string serverName;
int portNumber;
bool isConnected;
public:
SocketClient(std::string serverName, int portNumber);
virtual int connectToServer();
virtual int disconnectFromServer();
virtual int send(std::string message);
virtual std::string receive(int size);
bool isClientConnected() { return this->isConnected; }
virtual ~SocketClient();
};
}
#endif /* SOCKETCLIENT_H_ */

Can't open socket C++

I'm trying to send images (using IlpImage library) to VLan (media player) through the network so it can play streaming images and "make" a video.
I'm trying to open a socket but the value of "serversock" gives me always -1 and I don't understand why. I'm trying to search for this error but can't find a solution. Can someone help me?
Here's the code:
#include <stdio.h>
#include <stdlib.h>
#include <direct.h>
#include <iostream>
#include <WinSock2.h>
#include <Windows.h>
#include <iostream>
#include <string.h>
#include <time.h>
#include <errno.h>
//#include <fstream>
//#include "Packet.h"
#include <opencv2/core/core.hpp> // Basic OpenCV structures (cv::Mat, Scalar)
#include <opencv2/highgui/highgui.hpp> // OpenCV window I/O
using namespace std;
#define PORT 8888
#define GROUP "127.0.0.1"
int serversock, clientsock;
int is_data_ready = 0;
//methods
void quit(char* msg, int retval);
void sendImg (IplImage *img);
void sendImg(IplImage *img) {
struct sockaddr_in server;
int opt = 1;
/* setup server's IP and port */
memset(&server,0,sizeof(server));
server.sin_family = AF_INET;
server.sin_addr.s_addr = inet_addr(GROUP);
server.sin_port = htons(PORT);
//serversock = socket(AF_INET, SOCK_STREAM, 0);
serversock = socket(AF_INET, SOCK_DGRAM, 0);
While debbuging the value of serversock should be 0 and it gets -1, not continuing with the program.
if (serversock < 0) { // or == -1
quit("socket() failed", 1);
} //else {cout<< "Consegui!" << endl
cout << "socket() succeeded" << endl;
if(setsockopt(serversock,SOL_SOCKET,SO_BROADCAST, (const char*) &opt,sizeof(int))==-1){
quit("setsockopt failed",0);
}
/*
memset(&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(PORT);
server.sin_addr.s_addr = INADDR_ANY;*/
/* bind the socket */
if (bind(serversock, (const sockaddr*)&server, sizeof(server)) == -1) {
quit("bind() failed", 1);
}
/* wait for connection */
if (listen(serversock, 10) == -1) {
quit("listen() failed.", 1);
}
/* accept a client */
if ((clientsock = (int)accept(serversock, NULL, NULL)) == -1) {
quit("accept() failed", 1);
}
/* the size of the data to be sent */
int imgsize = img->imageSize;
int bytes=0;
//start sending images
if (is_data_ready) {
is_data_ready = 0;
if( (bytes = sendto(serversock, img->imageData, imgsize, 0, (struct sockaddr*)&server, sizeof(server)) ) == -1) {
quit("sendto FAILED", 1);
}
}
}
Use WSAGetLastError() to determine the cause of the failure:
if (serversocket < 0)
{
const DWORD last_error = WSAGetLastError();
// Pass 'last_error' to either the 'quit' function
// or log it somewhere else.
}
WSAStartup() is not present in the posted code and it must be called before using any of the socket API functions.

winsock compiling error, it cant find the addrinfo structures and some relating functions

I've just started learning winsock through the "Beej's guide to network programming" book. I'm programming under windows and running it through gcc. This is just a start to writing my first server program but it gives me these errors when I try to compile.
/* Server */
#include <iostream>
#include <windows.h>
#include <winsock2.h>
using namespace std;
const int winsockVersion = 2;
#define BACKLOG 10
#define PORT 3000
int main(void){
WSADATA wsadata;
if (WSAStartup(MAKEWORD(winsockVersion,0),&wsadata) == 0){
struct addrinfo hints, *res;
memset(&hints,0,sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
if ( getaddrinfo(NULL,PORT,&hints,&res) == 0 ){
cout<<"-Call to get addrinfo successful!." << endl;
}
cout<<"res af_family" << res->ai_family << endl;
}
//clear stuff
if( WSACleanup() != 0){
cout<<"-WSACleanup unsuccessful" << endl;
}else{
cout<<"-WSACleanup successful" << endl;
}
return 0;
}
these are the errors I'm receiving
g++ -o server.exe server.cpp -lws2_32
Process started >>>
server.cpp: In function `int main()':
server.cpp:20: error: aggregate `addrinfo hints' has incomplete type and cannot be defined
server.cpp:25: error: `AI_PASSIVE' was not declared in this scope
server.cpp:27: error: `getaddrinfo' was not declared in this scope
server.cpp:31: error: invalid use of undefined type `struct addrinfo'
server.cpp:20: error: forward declaration of `struct addrinfo'
server.cpp:54:2: warning: no newline at end of file
<<< Process finished.
Shouldn't the structures and functions be defined in either windows.h or winsock.h?.
SOLUTION
EDIT
to anyone who stumbles on this, add
#define _WIN32_WINNT 0x501
#include <ws2tcpip.h>
at the top of your source if getaddrinfo says that its undeclared.
You probably want to #include <ws2tcpip.h>. Remember that before Stack Overflow, Google is your friend for this kind of questions : you will get immediate answers from MSDN !
MSDN says we should #include <ws2tcpip.h>, but in ws2tcpip.h i found this piece of code:
#if (_WIN32_WINNT >= _WIN32_WINNT_WINXP)
/**
* For WIN2K the user includes wspiapi.h for these functions.
*/
void WSAAPI freeaddrinfo (struct addrinfo*);
int WSAAPI getaddrinfo (const char*,const char*,const struct addrinfo*,
struct addrinfo**);
int WSAAPI getnameinfo(const struct sockaddr*,socklen_t,char*,DWORD,
char*,DWORD,int);
#endif /* (_WIN32_WINNT >= _WIN32_WINNT_WINXP) */
this means, that _WIN32_WINNT is defined lower than _WIN32_WINNT_WINXP, but when i tried include wspiapi.h, i got "no such file or directory". My guess is, this is an fault of MinGW, where different parts of the library have inconsistent versions.
You have to #define _WIN32_WINNT _WIN32_WINNT_WINXP on your own, before including ws2tcpip.h
Beware! Your includes are wrong. The problem is that windows.h already includes winsock.h and winsock2.h then re-defines some structures and functions resulting in huge number of compilation errors. Move the windows.h include below the winsock2.h include, or just remove the windows.h include altogether, winsock2.h includes windows.h.
I was able to get this to work with the following includes, pragma, and defines...
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#pragma comment(lib, "ws2_32.lib")
The list of necessary includes for this answer are shown in a Microsoft article:
Winsock Includes
This is working for me:
#include <winsock2.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define DEFAULT_PORT 80
void error_die(const char *s)
{
fprintf(stderr, "Error: %s failed with error %d\n", s, WSAGetLastError());
WSACleanup();
exit(EXIT_FAILURE);
}
int main(int argc, char **argv)
{
char response[] = "HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=UTF-8\r\n\r\n"
"<!DOCTYPE html><html><head><title>Hello World</title></head>"
"<body><h1>Hello world!</h1></body></html>\r\n";
char buf[4096];
int msg_len, addr_len;
struct sockaddr_in local, client_addr;
SOCKET sock, msg_sock;
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) == SOCKET_ERROR)
{
fprintf(stderr, "WSAStartup failed with error %d\n", WSAGetLastError());
WSACleanup();
return -1;
}
// Fill in the address structure
local.sin_family = AF_INET;
local.sin_addr.s_addr = INADDR_ANY;
local.sin_port = htons(DEFAULT_PORT);
sock = socket(AF_INET, SOCK_STREAM, 0); //TCP socket
if (sock == INVALID_SOCKET)
error_die("socket()");
if (bind(sock, (struct sockaddr *)&local, sizeof(local)) == SOCKET_ERROR)
error_die("bind()");
if (listen(sock, 5) == SOCKET_ERROR) // wait for connection
error_die("listen()");
printf("Waiting for connection...\n");
while (1)
{
addr_len = sizeof(client_addr);
msg_sock = accept(sock, (struct sockaddr*)&client_addr, &addr_len);
if (msg_sock == INVALID_SOCKET || msg_sock == -1)
error_die("accept()");
printf("Accepted connection from %s, port %d\n", inet_ntoa(client_addr.sin_addr), htons(client_addr.sin_port));
msg_len = recv(msg_sock, buf, sizeof(buf), 0);
printf("Bytes Received: %d, message: %s from %s\n", msg_len, buf, inet_ntoa(client_addr.sin_addr));
msg_len = send(msg_sock, response, sizeof(response)-1 , 0);
if (msg_len == SOCKET_ERROR)
error_die("send()");
if (!msg_len)
{
printf("Client closed connection\n");
closesocket(msg_sock);
WSACleanup();
return -1;
}
closesocket(msg_sock);
}
WSACleanup();
}
In my case, I added struct when declaring sockaddr_in.
changed:
sockaddr_in m_sockAddr;
to
struct sockaddr_in m_sockAddr;
also,
bind(sock, (sockaddr*)&m_sockAddr, sizeof(m_sockAddrLsng ))
to
bind(m_sockLsng, (struct sockaddr*)&m_sockAddr, sizeof(m_sockAddr))