I'm developing a client-server program in c++ to transfer data from one computer to another.
Everything works fine but now I was asked to make it work on computers on different networks. I have searched everywhere but can't find a reliable solution.
I've seen the TCP hole punching solution but can't seem to find anywhere how to do it in c++.
I want it to work like teamviewer but without an intermediary server.
Connect my client (on one computer) to the server (on another computer in a different network) all programmatically.
#include "../include/ip_tunnel_ms_windows_20180815.h"
#include "../include/message_processor_common_20190410.h"
SOCKET clientSocket;
int n = 0;
void IPTunnel::initialize(void)
{
if (inputSignals.empty()) {
printf("server%d\n", n++);
if (!server()) {
printf("Error opening server\n");
::exit(1);
}
}
else {
printf("client%d\n", n++);
if (!client()) {
printf("Error opening client\n");
::exit(1);
}
}
}
bool IPTunnel::runBlock(void)
{
.....
(transmit data)
.....
return true;
}
void IPTunnel::terminate(void) {
closesocket(clientSocket);
WSACleanup();
}
bool IPTunnel::server() {
WSADATA wsData;
WORD ver = MAKEWORD(2, 2);
int wsOk = WSAStartup(ver, &wsData);
if (wsOk != 0)
{
cerr << "Can't Initialize winsock! Quitting" << endl;
return false;
}
SOCKET listening = socket(AF_INET, SOCK_STREAM, 0);
if (listening == INVALID_SOCKET)
{
cerr << "Can't create a socket! Quitting" << endl;
return false;
}
sockaddr_in hint;
hint.sin_family = AF_INET;
hint.sin_port = ntohs(tcpPort);
//inet_pton(AF_INET, (PCSTR)remoteMachineIpAddress.c_str(), &hint.sin_addr.s_addr); // hint.sin_addr.S_un.S_addr = inet_addr(ipAddressServer.c_str());
hint.sin_addr.S_un.S_addr = INADDR_ANY;
if (::bind(listening, (sockaddr*)& hint, sizeof(hint)) < 0) {
printf("\n ERROR on binding");
return false;
}
if (listen(listening, SOMAXCONN) == -1) {
printf("\n ERROR on binding");
return false;
}
sockaddr_in client;
int clientSize = sizeof(client);
clientSocket = accept(listening, (sockaddr*)& client, &clientSize);
char host[NI_MAXHOST];
char service[NI_MAXSERV];
ZeroMemory(host, NI_MAXHOST);
ZeroMemory(service, NI_MAXSERV);
if (getnameinfo((sockaddr*)& client, sizeof(client), host, NI_MAXHOST, service, NI_MAXSERV, 0) == 0)
{
cout << host << " connected on port " << service << endl;
}
else
{
inet_ntop(AF_INET, &client.sin_addr, host, NI_MAXHOST);
cout << host << " connected on port " <<
ntohs(client.sin_port) << endl;
}
return true;
}
bool IPTunnel::client() {
WSAData data;
WORD ver = MAKEWORD(2, 2);
int wsResult = WSAStartup(ver, &data);
if (wsResult != 0)
{
cerr << "Can't start Winsock, Err #" << wsResult << endl;
return false;
}
clientSocket = socket(AF_INET, SOCK_STREAM, 0);
if (clientSocket == INVALID_SOCKET)
{
cerr << "Can't create socket, Err #" << WSAGetLastError() << endl;
WSACleanup();
return false;
}
sockaddr_in hint;
hint.sin_family = AF_INET;
hint.sin_port = htons(tcpPort);
inet_pton(AF_INET, remoteMachineIpAddress.c_str(), &hint.sin_addr);
int connResult = -2;
while (connResult != 0 || numberOfTrials == 0) {
connResult = connect(clientSocket, (sockaddr*)& hint, sizeof(hint));
if (connResult == SOCKET_ERROR)
{
cerr << "Can't connect to server, Err #" << WSAGetLastError() << endl;
cerr << "Waiting " << timeIntervalSeconds << " seconds." << endl;
}
Sleep(timeIntervalSeconds * 1000);
;
if (--numberOfTrials == 0) {
cerr << "Reached maximum number of attempts." << endl;
::exit(1);
}
}
cout << "Connected!\n";
return true;
}
The definition of hole punching includes:
Both clients initiate a connection to an unrestricted server
You say:
I want it to work like teamviewer but without an intermediary server
That's not possible in general.
Related
I'm new to C++ Socket and my Server can't send message to its client. The send() function return -1 always and it seems to have a problem with accpSocket. However Client can do that smoothly and I don't know what's wrong. Please help me thank you so much!
Server
#include<WinSock2.h>
#include<WS2tcpip.h>
#include<iostream>
#include<sdkddkver.h>
#include<winsock.h>
using namespace std;
int main() {
SOCKET serverSocket, acceptSocket = INVALID_SOCKET;
int port = 2403;
WSADATA wsaData;
int wsaerr;
//Step 1: Set up dll
WORD versionRequested = MAKEWORD(2, 2);
wsaerr = WSAStartup(versionRequested, &wsaData);
if (wsaerr)
cout << "The winsock dll not found";
else {
cout << "The winsock dll found\n";
cout << "Winsock dll status: " << wsaData.szSystemStatus << endl;
}
//Step 2: Set up server socket
serverSocket = INVALID_SOCKET;
serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (serverSocket == INVALID_SOCKET) {
cout << "Error at socket: " << WSAGetLastError();
WSACleanup();
return 0;
}
else
cout << "Server socket successfull!\n";
//Step 3: Binding socket
sockaddr_in service;
service.sin_family = AF_INET;
service.sin_addr.S_un.S_addr = INADDR_ANY;
service.sin_port = htons(port);
if (bind(serverSocket, (sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) {
cout << "Binding failed! " << WSAGetLastError();
return 0;
}
else
cout << "Binding complete!\n";
// Step 4: Listen to the connections
if (listen(serverSocket, 1) == SOCKET_ERROR) {
cout << "Listen failed! " << WSAGetLastError();
return 0;
}
else
cout << "Waiting for connections ...";
SOCKET accpSocket = accept(serverSocket, NULL, NULL);
if (accpSocket == INVALID_SOCKET) {
cout << "Accepting failed! " << WSAGetLastError();
WSACleanup();
return -1;
}
else
cout << "Accept connection!\n";
char recvMess[2000];
char sendMess[2000];
int byterecv = recv(accpSocket, recvMess, sizeof(recvMess), 0);
cout << "Client: " << recvMess << endl;
cout << "Server: ";
cin.getline(sendMess, 2000);
int bytesend = send(acceptSocket, sendMess, 2000, 0);
if (bytesend <= 0)
cout << "Unsent";
return 0;
}
Client
#include<iostream>
#include<WinSock2.h>
#include<WS2tcpip.h>
using namespace std;
int main() {
int port = 2403;
WSADATA wsaData;
int wsaerr;
SOCKET clientSocket;
WORD versionRequested = MAKEWORD(2, 2);
wsaerr = WSAStartup(versionRequested, &wsaData);
if (wsaerr)
cout << "Winsock dll not found!";
else {
cout << "Winsock dll is ok!\n";
cout << "Status: " << wsaData.szSystemStatus << endl;
}
clientSocket = INVALID_SOCKET;
clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (clientSocket == INVALID_SOCKET) {
cout << "Set up client socket failed" << WSAGetLastError();
WSACleanup();
return 0;
}
else
cout << "Set up complete!\n";
sockaddr_in clientService;
clientService.sin_family = AF_INET;
clientService.sin_port = htons(port);
if (inet_pton(clientService.sin_family, "127.0.0.1", &clientService.sin_addr) <= 0) {
cout << "Invalid address!";
return -1;
}
if ((connect(clientSocket, (SOCKADDR*)&clientService, sizeof(clientService))) == SOCKET_ERROR) {
cout << "Connection failed!\n";
WSACleanup();
return 0;
}
else
cout << "Connection complete!\n";
char sendMess[2000];
char recvMess[2000];
cout << "Client: ";
cin.getline(sendMess, 2000);
int bytesend = send(clientSocket, sendMess, 2000, 0);
int byterecv = recv(clientSocket, recvMess, 2000, 0);
if (byterecv <= 0)
cout << "Nothing";
else
cout << "Server" << recvMess << endl;
return 0;
}
int bytesend = send(acceptSocket, sendMess, 2000, 0);
is not sending to a connected socket. acceptSocket was defined at the top of main and then ignored up until the call to send
As a general rule of thumb, keep variable definition close to first use.
In the server at
SOCKET serverSocket, acceptSocket = INVALID_SOCKET;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Killlllll meeeeee!!!!
remove acceptSocket to prevent future mistakes and in
int bytesend = send(acceptSocket, sendMess, 2000, 0);
replace acceptSocket with the socket that was actually accepted, accpSocket.
Side notes:
Never ignore the return codes.
int byterecv = recv(accpSocket, recvMess, sizeof(recvMess), 0);
could fail and return -1 or return 0 if the socket was disconnected, yet the program will still
cout << "Client: " << recvMess << endl;
And worse, there's no guarantee that recvMess will be null-terminated, recv on a streaming socket gives you what the socket has available or becomes available up to the maximum number of bytes requested, so if there is any data read, make sure byterecv is a valid index in recvMess by only reading sizeof(recvMess) - 1 bytes and then forcing termination with recvMess[byterecv] = '\0'; before printing.
send(acceptSocket, sendMess, 2000, 0); sends all 2000 bytes of sendMess regardless of how many bytes were read with cin.getline(sendMess, 2000);. Use
send(acceptSocket, sendMess, cin.gcount(), 0);
instead. Add on an extra byte (cin.gcount() + 1) if you want to send the null terminator.
I am writing a code of Image file transfer using socket programming.
Here, client is sending one request message to server for some file to send to client. After receiving message from client, server is sending text file to client.
But now I need to modify this to receive Image file instead of text file.
Please help me to solve the code for image transfer.
Here is the Server and Client code
//**server**
#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
#include <WS2tcpip.h>
#include <string>
#define SIZE 10241
#pragma comment (lib, "ws2_32.lib")
using namespace std;
void send_file(FILE* fp, int clientSocket) {
//int n;
char data[SIZE] = { 0 };
while (fgets(data, SIZE, fp) != NULL) {
if (send(clientSocket, data, sizeof(data), 0) == -1) {
perror("[-]Error in sending file.");
exit(1);
}
//bzero(data, SIZE);
//memset((data), '\0', (SIZE)), (void)0);
}
}
void main()
{
// Initialze winsock
WSADATA wsData;
WORD ver = MAKEWORD(2, 2);
int wsOk = WSAStartup(ver, &wsData);
if (wsOk != 0)
{
cerr << "Can't Initialize winsock! Quitting" << endl;
return;
}
// Create a socket
SOCKET listening = socket(AF_INET, SOCK_STREAM, 0);
if (listening == INVALID_SOCKET)
{
cerr << "Can't create a socket! Quitting" << endl;
return;
}
else
{
printf("socket created \n");
}
// Bind the ip address and port to a socket
sockaddr_in hint;
hint.sin_family = AF_INET;
hint.sin_port = htons(54000);
hint.sin_addr.S_un.S_addr = INADDR_ANY; // Could also use inet_pton ....
bind(listening, (sockaddr*)&hint, sizeof(hint));
// Tell Winsock the socket is for listening
//listen(listening, SOMAXCONN);
if (listen(listening, SOMAXCONN) == SOCKET_ERROR) {
printf("Listen failed with error: %ld\n", WSAGetLastError());
}
else {
printf("listening...\n");
}
// Wait for a connection
sockaddr_in client;
int clientSize = sizeof(client);
SOCKET clientSocket = accept(listening, (sockaddr*)&client, &clientSize);
char host[NI_MAXHOST]; // Client's remote name
char service[NI_MAXSERV]; // Service (i.e. port) the client is connect on
ZeroMemory(host, NI_MAXHOST); // same as memset(host, 0, NI_MAXHOST);
ZeroMemory(service, NI_MAXSERV);
if (getnameinfo((sockaddr*)&client, sizeof(client), host, NI_MAXHOST, service, NI_MAXSERV, 0) == 0)
{
cout << host << " connected on port " << service << endl;
}
else
{
inet_ntop(AF_INET, &client.sin_addr, host, NI_MAXHOST);
cout << host << " connected on port " <<
ntohs(client.sin_port) << endl;
}
FILE* fp = fopen("original.txt", "r");
// Close listening socket
//closesocket(listening);
if (fp == NULL) {
perror("[-]Error in reading file.");
exit(1);
}
// While loop: accept and echo message back to client
char buf[4096];
//while (true)
//{
ZeroMemory(buf, 4096);
// Wait for client to send data
int bytesReceived = recv(clientSocket, buf, 4096, 0);
if (bytesReceived > 0)
{
printf("Bytes received: %d\n", bytesReceived);
}
if (bytesReceived == SOCKET_ERROR)
{
//cerr << "Error in recv(). Quitting" << endl;
printf("recv failed: %d\n", WSAGetLastError());
// break;
}
if (bytesReceived == 0)
{
cout << "Client disconnected " << endl;
// break;
}
cout << string(buf, 0, bytesReceived) << endl;
// Echo message back to client
send(clientSocket, buf, bytesReceived + 1, 0);
send_file(fp, clientSocket);
printf("[+]File data sent successfully.\n");
printf("[+]Closing the connection.\n");
// Close the socket
closesocket(clientSocket);
//}
// Cleanup winsock
WSACleanup();
//system("pause");
}
//**client**
#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
#include <string>
#include <WS2tcpip.h>
#define SIZE 10241
#pragma comment(lib, "ws2_32.lib")
using namespace std;
void write_file(int sock) {
int n;
FILE* fp;
char buffer[SIZE];
fp = fopen("copy.txt", "w");
while (1) {
n = recv(sock, buffer, SIZE, 0);
if (n <= 0) {
break;
return;
}
fprintf(fp, "%s", buffer);
//(memset((buffer), '\0', (SIZE)));
}
fclose(fp);
return;
}
void main()
{
string ipAddress = "127.0.0.1"; // IP Address of the server
int port = 54000; // Listening port # on the server
// 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
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(port);
inet_pton(AF_INET, ipAddress.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;
}
// Do-while loop to send and receive data
//int new_sock;
//struct sockaddr_in new_addr;
//socklen_t addr_size;
//char buffer[SIZE];
//addr_size = sizeof(new_addr);
//new_sock = accept(listen_socket, (struct sockaddr*)&new_addr, &addr_size);
char buf[4096];
string userInput;
do
{
// Prompt the user for some text
cout << "Write Data : ";
getline(cin, userInput);
if (userInput.size() > 0) // Make sure the user has typed in something
{
// Send the text
int sendResult = send(sock, userInput.c_str(), userInput.size() + 1, 0);
if (sendResult != SOCKET_ERROR)
{
// Wait for response
ZeroMemory(buf, 4096);
int bytesReceived = recv(sock, buf, 4096, 0);
if (bytesReceived > 0)
{
// Echo response to console
cout << "SERVER : " << string(buf, 0, bytesReceived) << endl;
write_file(sock);
printf("Data received successfully\n");
}
}
}
break;
} while (userInput.size() > 0);
// close down everything
closesocket(sock);
WSACleanup();
}
Thanks.
void TCPConnectionV5::startServer()
{
/* Initialize Winsock */
int start;
sockaddr_in SERVER;
SERVER.sin_family = AF_INET;
SERVER.sin_addr.s_addr = INADDR_ANY;
//SERVER.sin_port = htons(stoi(DEFAULT_PORT));
SERVER.sin_port = htons(1787);
start = WSAStartup(MAKEWORD(2, 2), &_wsaData);
if (start != 0)
{
cout << "Error on WSAStartup: " << start << endl;
}
/* Create socket that will connect to server */
_listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
_socketCollection.push_back(_listener);
if (_listener == INVALID_SOCKET)
{
cout << "Error creating socket to connect to server: " << WSAGetLastError() << endl;
WSACleanup();
}
/* Bind the socket */
start = bind(_listener, (sockaddr*)&SERVER, sizeof(SERVER));
if (start == SOCKET_ERROR)
{
cout << "Error on bind:" << WSAGetLastError() << endl;
closesocket(_listener);
WSACleanup();
}
/* Create the listener socket */
start = listen(_listener, 16);
if (start == SOCKET_ERROR)
{
cout << "Error on entering the listening state: " << start << endl;
closesocket(_listener);
WSACleanup();
}
printTime();
cout << "Server entered listening state" << endl;
/* Create the thread */
sockaddr_in client;
int clientSize = sizeof(client);
while (true)
{
SOCKET messager = accept(_listener, (struct sockaddr*)&client, &clientSize);
_socketCollection.push_back(messager);
locker.lock();
printTime();
if (messager != SOCKET_ERROR)
{
cout << "Client Connection success!" << endl;
cout << "Messager: " << messager << endl;
locker.unlock();
std::thread newThread([&] {this->exchange(messager); });
newThread.detach();
}
else
{
locker.unlock();
}
}
}
DWORD TCPConnectionV5::exchange(SOCKET messager)
{
int bytesSent = sendMessage(messager, msg);
if (bytesSent <= 0)
{
closesocket(messager);
return -1;
}
int bytesReceived = receiveMessage(messager);
if (bytesReceived <= 0)
{
closesocket(messager);
return -1;
}
}
I noticed that when the server connects with multiple clients, that there sometimes appear to be duplicate messages that send to some clients, which is accompanied by missing messages to another client application. I have mutex lock/unlock in place for sending/receiving messages, but what's causing these duplicate/missing messages? Is there some underlying issue I have to address regarding the threads?
I'm trying to create a server client that once its working I can pass a vector into it and send it to a client program through ssh like putty. The issue is whenever I try to connect raw or ssh with putty on 127.0.0.1:45000 the program terminates once it connects.
Here is my code:
#include <iostream>
#include <WS2tcpip.h>
#include <string>
#pragma comment (lib, "ws2_32.lib")
using namespace std;
void main()
{
// Initialize winsock
WSADATA wsData;
WORD ver = MAKEWORD(2, 2);
int wsOk = WSAStartup(ver, &wsData);
if (wsOk != 0)
{
cerr << "Can't Intitialze winsock! Quiting" << endl;
return;
}
// Create a socket to bind
SOCKET listening = socket(AF_INET, SOCK_STREAM, 0);
if (listening == INVALID_SOCKET)
{
cerr << "Can't create a socket! Quitting" << endl;
}
// Bind the socket to an ip address to the port
sockaddr_in hint;
hint.sin_family = AF_INET;
hint.sin_port = htons(45000);
hint.sin_addr.S_un.S_addr = INADDR_ANY; // could also use inet_pton
bind(listening, (sockaddr*)&hint, sizeof(hint));
// Tell winsock the socket is for listening
listen(listening, SOMAXCONN);
// Wait for connection
sockaddr_in client;
int clientSize = sizeof(client);
SOCKET clientSocket = accept(listening, (sockaddr*)&client, &clientSize);
char host[NI_MAXHOST]; //Clients remote name
char service[NI_MAXHOST]; // Service (port) the client is on
ZeroMemory(host, NI_MAXHOST);
ZeroMemory(service, NI_MAXHOST); // use mem set of linux
if (getnameinfo((sockaddr*)&client, sizeof(client), host, NI_MAXHOST, service, NI_MAXSERV, 0) == 0)
{
cout << host << " connected on port " << service << endl;
return;
}
else
{
inet_ntop(AF_INET, &client.sin_addr, host, NI_MAXHOST);
cout << host << " connected on port " <<
ntohs(client.sin_port) << endl;
return;
}
// Close listening socket
closesocket(listening);
// while loop; accept and echo message back to client
char buf[4096];
while (true)
{
ZeroMemory(buf, 4096);
// wait for client to send data
int bytesReceived = recv(clientSocket, buf, 4096, 0);
if (bytesReceived == SOCKET_ERROR)
{
cerr << "Error in recv(). Quitting" << endl;
break;
}
if (bytesReceived == 0)
{
cout << "Client Disconnected, bytes 0" << endl;
break;
}
// echo message back to client
send(clientSocket, buf, bytesReceived + 1, 0);
// Close the socket
}
closesocket(clientSocket);
// Shutdown winsock
WSACleanup();
}
I'm writing it and compiling in Visual Studio 2019.
Here's the message I get from Putty when trying to connect with the ssh option or raw.
If anyone can help it would be greatly appreciated. Thanks!
When calling getnameinfo(), you are return'ing from main() immediately, without calling closesocket() first, regardless of whether getnameinfo() is successful or fails. This is the root of your Putty error. You are explicitly exiting your app whenever a client connects, without informing the client that the connection is being closed.
More generally, if accept() is successful (and socket(), too), you should always call closesocket() on the returned SOCKET, regardless of anything else happening in your code (same with WSACleanup() if WSAStartup() is successful).
There are several other mistakes in your code:
It is illegal for main() to have a non-int return type (though some compilers allow this, as a non-standard extension. Don't rely on this!).
You are missing a return from main() if socket() fails.
You are not checking for errors on bind(), listen(), accept(), or send().
There is no point in setting the backlog to SOMAXCONN if you are only going to accept() 1 client ever.
you have a potential buffer overflow when calling send(). Imagine if recv() returned exactly 4096 bytes received. Sending bytesReceived + 1 number of bytes back to the client would go out of bounds of your buf array.
With that said, try something more like this:
#include <iostream>
#include <WS2tcpip.h>
#include <string>
#pragma comment (lib, "ws2_32.lib")
using namespace std;
int main()
{
// Initialize winsock
WSADATA wsData;
WORD ver = MAKEWORD(2, 2);
int errCode = WSAStartup(ver, &wsData);
if (errCode != 0)
{
cerr << "Can't initialize winsock! Error " << errCode << ". Quitting" << endl;
return 0;
}
// Create a socket to bind
SOCKET listening = socket(AF_INET, SOCK_STREAM, 0);
if (listening == INVALID_SOCKET)
{
errCode = WSAGetLastError();
cerr << "Can't create listening socket! Error " << errCode << ". Quitting" << endl;
WSACleanup();
return 0;
}
// Bind the socket to an ip address to the port
sockaddr_in hint = {};
hint.sin_family = AF_INET;
hint.sin_port = htons(45000);
hint.sin_addr.s_addr = INADDR_ANY; // could also use inet_pton
if (bind(listening, (sockaddr*)&hint, sizeof(hint)) == SOCKET_ERROR)
{
errCode = WSAGetLastError();
cerr << "Can't bind listening socket! Error " << errCode << ". Quitting" << endl;
closesocket(listening);
WSACleanup();
return 0;
}
// Tell winsock the socket is for listening
if (listen(listening, 1) == SOCKET_ERROR)
{
errCode = WSAGetLastError();
cerr << "Can't open listening socket! Error " << errCode << ". Quitting" << endl;
closesocket(listening);
WSACleanup();
return 0;
}
// Wait for connection
sockaddr_in client;
int clientSize = sizeof(client);
SOCKET clientSocket = accept(listening, (sockaddr*)&client, &clientSize);
if (clientSocket == INVALID_SOCKET)
{
errCode = WSAGetLastError();
cerr << "Can't accept a client! Error " << errCode << ". Quitting" << endl;
closesocket(listening);
WSACleanup();
return 0;
}
char host[NI_MAXHOST]; //Clients remote name
char service[NI_MAXHOST]; // Service (port) the client is on
ZeroMemory(host, NI_MAXHOST);
ZeroMemory(service, NI_MAXHOST); // use mem set of linux
if (getnameinfo((sockaddr*)&client, clientSize, host, NI_MAXHOST, service, NI_MAXSERV, 0) == 0)
{
cout << host << " connected on port " << service << endl;
}
else
{
inet_ntop(AF_INET, &(client.sin_addr), host, NI_MAXHOST);
cout << host << " connected on port " << ntohs(client.sin_port) << endl;
}
// Close listening socket
closesocket(listening);
listening = INVALID_SOCKET;
// while loop; accept and echo message back to client
char buf[4096];
while (true)
{
// wait for client to send data
int bytesReceived = recv(clientSocket, buf, sizeof(buf), 0);
if (bytesReceived == SOCKET_ERROR)
{
errCode = WSAGetLastError();
cerr << "Error reading from client: " << errCode << ". Quitting" << endl;
break;
}
if (bytesReceived == 0)
{
cout << "Client Disconnected" << endl;
break;
}
// echo message back to client
char *ptr = buf;
int bytesToSend = bytesReceived;
do
{
int bytesSent = send(clientSocket, ptr, bytesToSend, 0);
if (bytesSent == SOCKET_ERROR)
break;
ptr += bytesSent;
bytesToSend -= bytesSent;
}
while (bytesToSend > 0);
if (bytesToSend != 0)
{
errCode = WSAGetLastError();
cerr << "Error writing to client: " << errCode << ". Quitting" << endl;
break;
}
}
// Close the client socket
closesocket(clientSocket);
// Shutdown winsock
WSACleanup();
return 0;
}
//UDP receiver
int main()
{
WSAData wsaData;
SOCKET receivingSocket;
SOCKADDR_IN receiverAddr;
SOCKADDR_IN senderAddr;
int senderAddrSize = sizeof(senderAddr);
int port=51020;
char receiveBuf[1024];
int bufLength=1024;
cout << "UDP receiver\n";
//Initialize winsock
if (WSAStartup(MAKEWORD(2,2),&wsaData) != 0)
{
cout << "Failed. Error Code : " << WSAGetLastError();
exit(EXIT_FAILURE);
}
cout << "Initialised\n";`
if(receivingSocket = socket(AF_INET, SOCK_DGRAM, 0 ) == INVALID_SOCKET )
{
cout << "Could not create socket :" << WSAGetLastError();
}
cout << "Socket created.\n";
//fill up SOCKADDR_IN structure
senderAddr.sin_port = htons(port);
senderAddr.sin_family = AF_INET;
senderAddr.sin_addr.s_addr = htonl(INADDR_ANY);
//Bind information with socket
bind(receivingSocket, (SOCKADDR*)&senderAddr, sizeof(senderAddr));
while(1)
{
cout << "Waiting for message\n";
//try to receive some data, this is a blocking call
if (recvfrom(receivingSocket, receiveBuf, 1024, 0, (SOCKADDR*)&senderAddr, &senderAddrSize)) == SOCKET_ERROR))
{
cout << "recvfrom() failed with error code :" << WSAGetLastError();
exit(EXIT_FAILURE);
}
cout << receiveBuf;
}
//Close socket
closesocket(receivingSocket);
WSACleanup();
std::cin.get();
return 0;
}
//UDP server
int main()
{
WSAData wsaData;
SOCKET sendingSocket;
SOCKADDR_IN receiverAddr;
int port = 51010;
char sendBuf[1024]="Hello!!!";
int bufLength = 1024;
cout << "UDP server from book\n";
//Initialize socket
if (WSAStartup(MAKEWORD(2,2),&wsaData) != 0)
{
cout << "Failed. Error Code : " << WSAGetLastError();
exit(EXIT_FAILURE);
}
cout << "Initialised\n";
if(sendingSocket = socket(AF_INET, SOCK_DGRAM, 0) == INVALID_SOCKET)
{
cout << "Could not create socket : " << WSAGetLastError();
}
cout << "Socket created.\n";
//FIll out structure of receiverAdd
receiverAddr.sin_family = AF_INET;
receiverAddr.sin_port = htons(port);
receiverAddr.sin_addr.s_addr = inet_addr("192.168.1.100");
int test = bind(sendingSocket, (SOCKADDR*)&receiverAddr, sizeof(receiverAddr));
if( test < 0)
{
cout << "Bind failed with error code : %d" << WSAGetLastError();
exit(EXIT_FAILURE);
}
cout << "Bind is successful\n";
while(1)
{
cout << "Sending data...\n";
//Send datagram to receiver
if(sendto(sendingSocket, sendBuf, 1024, 0, (SOCKADDR*)&receiverAddr, sizeof(receiverAddr)) == SOCKET_ERROR)
{
cout << "sendto() failed with error code : " << WSAGetLastError();
exit(EXIT_FAILURE);
}
cout << "Sent";
}
//close socket
closesocket(sendingSocket);
WSACleanup();
std::cin.get();
// return 0;
}
Error 10038 is WSAENOTSOCK: The descriptor is not a socket.
You are calling socket() and assigning your SOCKET handles inside of if statements, but you are missing adequate parenthesis. They should be like this instead:
if( (receivingSocket = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET )
if( (sendingSocket = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET )
Personally, I hate code that performs assignments inside of if statements like this. I prefer to keep them separate. It is cleaner, less error-prone, and no less efficient from the compiler's perspective:
receivingSocket = socket(AF_INET, SOCK_DGRAM, 0);
if( receivingSocket == INVALID_SOCKET )
sendingSocket = socket(AF_INET, SOCK_DGRAM, 0);
if( sendingSocket == INVALID_SOCKET )
On a side note:
WSAStartup() does not use WSAGetLastError() for error reporting, it directly returns an error code instead. This is clearly stated in the WSAStartup() documentation.
int err = WSAStartup(MAKEWORD(2,2),&wsaData);
if (err != 0)
{
cout << "Failed. Error Code : " << err;
exit(EXIT_FAILURE);
}
your UDP receiver is not checking the return value of bind() for an error before entering the recvfrom() loop.