Check port availability with boost - c++

I'm trying to check whether port on my pc is available or not. But this code crashes after the acceptor.listen();. Crash stack trace stops at:
detail/impl/win_iocp_socket_service_base.ipp
My code is:
try {
boost::asio::io_service io_service;
boost::asio::ip::tcp::acceptor acceptor(io_service);
boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::address::from_string("127.0.0.1"), port);
acceptor.open(endpoint.protocol());
acceptor.set_option(boost::asio::ip::tcp::acceptor::reuse_address(false));
acceptor.bind(endpoint);
acceptor.listen();
}
catch (...) {
// port busy
}
How can I check this with boost or where is the problem in my code?
UPD1: I tried following code from here:
bool port_in_use(unsigned short port) {
using namespace boost::asio;
using ip::tcp;
io_service svc;
tcp::acceptor a(svc);
boost::system::error_code ec;
a.open(tcp::v4(), ec) || a.bind({ tcp::v4(), port }, ec);
return ec == error::address_in_use;
}
but after function executes, my program crashes still in same place.

Well, I found how to do this in windows (from link):
#ifndef UNICODE
#define UNICODE
#endif
#define WIN32_LEAN_AND_MEAN
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
// Need to link with Ws2_32.lib
#pragma comment(lib, "ws2_32.lib")
int wmain()
{
//----------------------
// Initialize Winsock
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != NO_ERROR) {
wprintf(L"WSAStartup function failed with error: %d\n", iResult);
return 1;
}
//----------------------
// Create a SOCKET for connecting to server
SOCKET ConnectSocket;
ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ConnectSocket == INVALID_SOCKET) {
wprintf(L"socket function failed with error: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
//----------------------
// The sockaddr_in structure specifies the address family,
// IP address, and port of the server to be connected to.
sockaddr_in clientService;
clientService.sin_family = AF_INET;
clientService.sin_addr.s_addr = inet_addr("127.0.0.1");
clientService.sin_port = htons(27015);
//----------------------
// Connect to server.
iResult = connect(ConnectSocket, (SOCKADDR *) & clientService, sizeof (clientService));
if (iResult == SOCKET_ERROR) {
wprintf(L"connect function failed with error: %ld\n", WSAGetLastError());
iResult = closesocket(ConnectSocket);
if (iResult == SOCKET_ERROR)
wprintf(L"closesocket function failed with error: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
wprintf(L"Connected to server.\n");
iResult = closesocket(ConnectSocket);
if (iResult == SOCKET_ERROR) {
wprintf(L"closesocket function failed with error: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
WSACleanup();
return 0;
}

Related

C++ Run time memory error with winsock on virtual nat network

I have a Server that I wrote that parses the computer's filesystem into a vector. A client then connects to the server with Putty or netcat and receives the vector of the parsed filesystem.
This works fine locally on one machine with 127.0.0.1.
However, when I transfer the code to a virtual environment in VirtualBox on a 10.0.0.0 NAT network, I receive a memory error.
Any ideas how to fix this?
Here is my code:
#undef UNICODE
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
#include <fstream>
#include <iostream>
#include <filesystem>
#include <vector>
#include <string>
namespace fs = std::filesystem;
std::vector<std::string> get_all_files_recurisive(const std::string& path)
{
std::vector<std::string> file_names;
using iterator = fs::recursive_directory_iterator;
for (iterator iter(path); iter != iterator{}; ++iter)
file_names.push_back(iter->path().string());
return file_names;
}
// Need to link with Ws2_32.lib
#pragma comment (lib, "Ws2_32.lib")
// #pragma comment (lib, "Mswsock.lib")
#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "45000"
#define DEFAULT_ADDRS "10.0.2.5"
int __cdecl main(void)
{
WSADATA wsaData;
int iResult;
SOCKET ListenSocket = INVALID_SOCKET;
SOCKET ClientSocket = INVALID_SOCKET;
struct addrinfo* result = NULL;
struct addrinfo hints;
int iSendResult;
char recvbuf[DEFAULT_BUFLEN];
int recvbuflen = DEFAULT_BUFLEN;
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed with error: %d\n", iResult);
return 1;
}
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
// Resolve the server address and port
iResult = getaddrinfo(DEFAULT_ADDRS, DEFAULT_PORT, &hints, &result);
if (iResult != 0) {
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
return 1;
}
// Create a SOCKET for connecting to server
ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if (ListenSocket == INVALID_SOCKET) {
printf("socket failed with error: %ld\n", WSAGetLastError());
freeaddrinfo(result);
WSACleanup();
return 1;
}
// Setup the TCP listening socket
iResult = bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen);
if (iResult == SOCKET_ERROR) {
printf("bind failed with error: %d\n", WSAGetLastError());
freeaddrinfo(result);
closesocket(ListenSocket);
WSACleanup();
return 1;
}
freeaddrinfo(result);
iResult = listen(ListenSocket, SOMAXCONN);
if (iResult == SOCKET_ERROR) {
printf("listen failed with error: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
return 1;
}
// Accept a client socket
ClientSocket = accept(ListenSocket, NULL, NULL);
if (ClientSocket == INVALID_SOCKET) {
printf("accept failed with error: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
return 1;
}
// No longer need server socket
closesocket(ListenSocket);
// Receive until the peer shuts down the connection
do {
std::string SendIresult = "";
const std::vector<std::string> file_list = get_all_files_recurisive("C:\\Users");
for (const auto& fn : file_list) {
// Convert fn vector in the for loop to sendable data
const char* sendbuf = fn.data();
iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
if (iResult > 0) {
printf("Bytes received: %d\n", iResult);
// Echo the fn vector list to the sender
iResult = send(ClientSocket, sendbuf, (int)strlen(sendbuf), 0);
if (iResult == SOCKET_ERROR) {
printf("send failed with error: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
return 1;
}
printf("Bytes sent: %d\n", iResult);
}
else if (iResult == 0)
printf("Connection closing...\n");
else {
printf("recv failed with error: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
return 1;
}
}
} while (iResult > 0);
// shutdown the connection since we're done
iResult = shutdown(ClientSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf("shutdown failed with error: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
return 1;
}
// cleanup
closesocket(ClientSocket);
WSACleanup();
return 0;
}
Here is the error when I run it in Visual Studio on the VM and tried connecting with netcat from my parrot-os Linux on the same network:
Here is the error message in text:
Unhandled exception at 0x75772552 in Project3.exe: Microsoft C++
exception: std::system_error at memory location 0x0141EA50.
It happens right after this line in the beginning.
using iterator = fs::recursive_directory_iterator;
for (iterator iter(path); iter != iterator{}; ++iter)
Just for context, this code is not being published, so it doesn't need to be the prettiest code written. It's for an Exploit dev project.
You are seeing a message from the Visual Studio debugger. It is telling you that the code is throwing a std::system_error exception that you are not handling.
The recursive_directory_iterator constructor you are calling throws a std::filesystem::filesystem_error exception (a derivative of std::system_error) if the underlying OS filesystem API fails, such as if the provided path is invalid, etc. So, you need to either:
catch that exception and handle it:
try
{
for (iterator iter(path); iter != iterator{}; ++iter)
file_names.push_back(iter->path().string());
}
catch (const fs::filesystem_error &e)
{
// do something, such as logging the values of e.what(), e.path1(), and e.code() ...
}
use the overloaded constructor, and increment() method, which take a std::error_code& output parameter:
std::error_code ec;
iterator iter(path, ec);
while ((!ec) && (iter != iterator{})){
file_names.push_back(iter->path().string());
iter.increment(ec);
}
if (ec) {
// do something, such as logging the values of ec.value() and ec.message() ...
}

std::thread throwing Unhandled exception: Access violation reading location [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm trying to get multi threading working on my simple server project. It was working fine on my laptop, yet when I moved the project folder to my desktop, it gives me an unhandled exception at my std::thread call.
I have a method StartAcceptingClients() which works fine when unthreaded and called on it's own. However when I call it by new thread:
std::thread clientsThread(StartAcceptingClients);
It throws:
Unhandled exception at 0x62E50BD0 in WinsockServer.exe: 0xC0000005: Access violation reading location 0x62E50BD0.
MCVE:
#pragma once
#undef UNICODE
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <string>
#include <thread>
// Need to link with Ws2_32.lib
#pragma comment (lib, "Ws2_32.lib")
// #pragma comment (lib, "Mswsock.lib")
#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "27015"
#include "Client.h"
WSADATA wsaData;
int iResult;
SOCKET ListenSocket = INVALID_SOCKET;
SOCKET ClientSocket = INVALID_SOCKET;
struct addrinfo *result = NULL;
struct addrinfo hints;
int iSendResult;
char recvbuf[DEFAULT_BUFLEN];
int recvbuflen = DEFAULT_BUFLEN;
const int MAXUSERS = 8;
Client* clients[MAXUSERS];
void ListenForNewClient()
{
//Listen to socket
printf("Listening for connections...\n");
iResult = listen(ListenSocket, SOMAXCONN);
if (iResult == SOCKET_ERROR) {
printf("listen failed with error: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
std::cin.get();
return;// 1;
}
}
Client* AcceptNewClient()
{
// Accept a client socket
ClientSocket = accept(ListenSocket, NULL, NULL);
if (ClientSocket == INVALID_SOCKET) {
printf("accept failed with error: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
std::cin.get();
return NULL;// 1;
}
Client* client = new Client(); client->socket = ClientSocket;
for (int i = 0; i < MAXUSERS; i++)
{
if (clients[i] == NULL)
{
clients[i] = client;
clients[i]->clientID = i;
printf("Client %i has joined.\n", i);
break;
}
}
// No longer need server socket
closesocket(ListenSocket);
return client;
}
void StartRecievingFromClient(Client* client)
{
// Receive until the peer shuts down the connection
do {
iResult = recv(client->socket, recvbuf, recvbuflen, 0);
if (iResult > 0) {
printf("Bytes received: %d\n", iResult);
// Echo the buffer back to the sender
iSendResult = send(client->socket, recvbuf, iResult, 0);
if (iSendResult == SOCKET_ERROR) {
printf("send failed with error: %d\n", WSAGetLastError());
closesocket(client->socket);
WSACleanup();
std::cin.get();
return;// 1;
}
printf("Bytes sent: %d\n", iSendResult);
}
else if (iResult == 0)
printf("Client %i has disconnected.\n", client->clientID);
else {
printf("recv failed with error: %d\n", WSAGetLastError());
closesocket(client->socket);
WSACleanup();
std::cin.get();
return;// 1;
}
} while (iResult > 0);
}
void StartAcceptingClients()
{
ListenForNewClient();
Client* client = AcceptNewClient();
client->listenThread = new std::thread(StartRecievingFromClient, client);
}
//int __cdecl main(void)
int main()
{
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed with error: %d\n", iResult);
std::cin.get();
return 1;
}
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
// Resolve the server address and port
iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
if (iResult != 0) {
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
std::cin.get();
return 1;
}
// Create a SOCKET for connecting to server
ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if (ListenSocket == INVALID_SOCKET) {
printf("socket failed with error: %ld\n", WSAGetLastError());
freeaddrinfo(result);
WSACleanup();
std::cin.get();
return 1;
}
// Setup the TCP listening socket
iResult = bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen);
if (iResult == SOCKET_ERROR) {
printf("bind failed with error: %d\n", WSAGetLastError());
freeaddrinfo(result);
closesocket(ListenSocket);
WSACleanup();
std::cin.get();
return 1;
}
freeaddrinfo(result);
std::thread clientsThread(StartAcceptingClients);
printf("Game Loop Started.\n");
//Game Loop
while (true)
{
std::string Command;
std::getline(std::cin, Command);
}
printf("Game Loop Ended.\n");
// shutdown the connection since we're done
iResult = shutdown(ClientSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf("shutdown failed with error: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
std::cin.get();
return 1;
}
// cleanup
closesocket(ClientSocket);
WSACleanup();
std::cin.get();
return 0;
}

C++ server unable to receive data from client / Winsock

I am working on a simple client-server application. However, after client runs, i get the message error 10038 with the recv(), in the server side. The socket number descriptor retains the same value in both client and server, thus i think there is no a socket error. Any help would be appreciated.
client:
#ifndef UNICODE
#define UNICODE
#endif
#define WIN32_LEAN_AND_MEAN
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
// Need to link with Ws2_32.lib.
#pragma comment(lib, "ws2_32.lib")
int wmain()
{
// Initialize Winsock.
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != NO_ERROR) {
printf("WSAStartup() failed with error: %d\n", iResult);
return 1;
}
// Create a socket for connecting to server.
SOCKET ConnectSocket;
ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ConnectSocket == INVALID_SOCKET) {
printf("socket() failed with error: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
printf("Socket descriptor: %d\n",ConnectSocket);
// The sockaddr_in structure specifies the address family,
// IP address, and port of the server to be connected to.
sockaddr_in Service;
memset(&Service, 0, sizeof(Service));
Service.sin_family = AF_INET;
Service.sin_addr.s_addr = inet_addr("127.0.0.1");
Service.sin_port = htons(27015);
// Connect to server.
iResult = connect(ConnectSocket, (SOCKADDR *) &Service, sizeof (Service));
if (iResult == SOCKET_ERROR) {
printf("connect() failed with error: %ld\n", WSAGetLastError());
iResult = closesocket(ConnectSocket);
if (iResult == SOCKET_ERROR)
printf("closesocket() failed with error: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
printf("Connected to server.\n");
// Message that has to be sent.
char receiveBuffer[1000];
char message[1000];
printf("\nEnter message: ");
gets_s(message);
printf("Message you wrote is: %s\n", message);
// Send a message.
if (send(ConnectSocket, message, sizeof(message), 0) == SOCKET_ERROR)
{
printf("send() failed with error code: %d\n", WSAGetLastError());
}
printf("Message successfully sent to server.");
// Receive a message.
if (recv(ConnectSocket, receiveBuffer, 1000, 0) == SOCKET_ERROR)
{
printf("recv() failed with error code: %d\n", WSAGetLastError());
while(1);
}
printf("\nServer says:");
printf(receiveBuffer,sizeof(receiveBuffer));
while(1);
closesocket(ConnectSocket);
WSACleanup();
return 0;
}
server:
#ifndef UNICODE
#define UNICODE
#endif
#define WIN32_LEAN_AND_MEAN
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
// Need to link with Ws2_32.lib
#pragma comment(lib, "ws2_32.lib")
int wmain()
{
// Initialize Winsock.
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != NO_ERROR) {
printf("WSAStartup() failed with error: %d\n", iResult);
return 1;
}
// Create a socket for connecting to client.
SOCKET ConnectSocket;
ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ConnectSocket == INVALID_SOCKET) {
printf("socket() failed with error: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
printf("Socket descriptor: %d\n", ConnectSocket);
// The sockaddr_in structure specifies the address family,
// IP address, and port of the server to be connected to.
sockaddr_in Service;
memset(&Service, 0, sizeof(Service));
Service.sin_family = AF_INET;
Service.sin_addr.s_addr = inet_addr("127.0.0.1");
Service.sin_port = htons(27015);
//Bind.
if (bind(ConnectSocket, (struct sockaddr *)&Service, sizeof(Service)) == SOCKET_ERROR)
{
printf("Bind failed with error code: %d\n" , WSAGetLastError());
}
printf("Bind done.\n");
// Listen on the socket for a client.
if (listen(ConnectSocket, 1) == SOCKET_ERROR)
{
printf ("listen() failed with error: %ld\n", WSAGetLastError() );
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
printf("listen() run successfully.\n");
// Accept a connection from a client.
SOCKET acceptSocket;
acceptSocket = accept(ConnectSocket, NULL, NULL);
if (acceptSocket == INVALID_SOCKET) {
printf("accept() failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
else{
printf("accept() run successfully.\n");
}
// No longer need server socket.
closesocket(ConnectSocket);
char receiveBuffer[1000];
int recv_len;
printf("\nWaiting for data...\n");
fflush(stdout);
// Receive a message.
if (recv_len = recv(ConnectSocket, receiveBuffer, 1000, 0) == SOCKET_ERROR)
{
printf("Socket descriptor, after recv(): %d\n", ConnectSocket);
printf("recv() failed with error code: %d\n", WSAGetLastError());
while(1);
}
// Send a message.
if (send(ConnectSocket, receiveBuffer, recv_len, 0) == SOCKET_ERROR)
{
printf("sendto() failed with error code: %d\n", WSAGetLastError());
while(1);
}
else
printf("\nMessage sent back to client.");
while(1);
closesocket(ConnectSocket);
WSACleanup();
return 0;
}
I am a beginner at Winsock programming and any help would be appreciated.
Error 10038 is WSAENOTSOCK, which means you do not have a valid socket. On the server side, you are using the server socket (ConnectSocket) after you have closed it. To receive and send, you need to use the connected socket (acceptSocket) instead. Also, you need to close acceptSocket when you are done with it, do not close ConnectSocket a second time.

Unable to send data over windows UDP sockets:Error Code 10035

I am trying to receive data on a program from another program running on the same windows 7 pc through sockets. For this i have made two separate program, one for sending and other for receiving.Send program is showing success but receive program is waiting indefinitely.when i put the receive socket in non blocking mode i am receiving error code 10035 ie resource unavailable. Is there any system setting i have to do like firewall or any thing. Although after disabling firewall i am getting same error.I searched the stackoverflow.com but could not get solution to my problem.
I am giving the code below for send and receive functions.
For Send Function:
#include "stdafx.h"
#ifndef UNICODE
#define UNICODE
#endif
#define WIN32_LEAN_AND_MEAN
#include <winsock2.h>
#include <Ws2tcpip.h>
#include <stdio.h>
// Link with ws2_32.lib
#pragma comment(lib, "Ws2_32.lib")
using namespace System;
int main(array<System::String ^> ^args)
{
char ch;
int iRun =1;
int iResult;
WSADATA wsaData;
SOCKET SendSocket = INVALID_SOCKET;
sockaddr_in RecvAddr;
unsigned short Port = 51234;
char SendBuf[1024]="Testing";
int BufLen = 1024;
//----------------------
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != NO_ERROR) {
wprintf(L"WSAStartup failed with error: %d\n", iResult);
return 1;
}
//---------------------------------------------
// Create a socket for sending data
SendSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (SendSocket == INVALID_SOCKET) {
wprintf(L"socket failed with error: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
//---------------------------------------------
// Set up the RecvAddr structure with the IP address of
// the receiver (in this example case "178.0.0.100")
// and the specified port number.
RecvAddr.sin_family = AF_INET;
RecvAddr.sin_port = htons(Port);
RecvAddr.sin_addr.s_addr = inet_addr("178.0.0.100");
//---------------------------------------------
// Send a datagram to the receiver
wprintf(L"Sending a datagram to the receiver...\n");
while(iRun) {
iResult = sendto(SendSocket,
SendBuf, BufLen, 0, (SOCKADDR *) & RecvAddr, sizeof (RecvAddr));
if (iResult == SOCKET_ERROR) {
wprintf(L"sendto failed with error: %d\n", WSAGetLastError());
//closesocket(SendSocket);
//WSACleanup();
//return 1;
}
wprintf(L"send success :data bytes: %d\n", iResult);
}
//---------------------------------------------
// When the application is finished sending, close the socket.
wprintf(L"Finished sending. Closing socket.\n");
iResult = closesocket(SendSocket);
if (iResult == SOCKET_ERROR) {
wprintf(L"closesocket failed with error: %d\n", WSAGetLastError());
WSACleanup();
return 1;
}
//---------------------------------------------
scanf("enter any number to terminate %c",&ch);
// Clean up and quit.
wprintf(L"Exiting.\n");
WSACleanup();
return 0;
//Console::WriteLine(L"Hello World");
//return 0;
}
For Receive Function
#include "stdafx.h"
#ifndef UNICODE
#define UNICODE
#endif
#define WIN32_LEAN_AND_MEAN
#include <winsock2.h>
#include <Ws2tcpip.h>
#include <stdio.h>
// Link with ws2_32.lib
#pragma comment(lib, "Ws2_32.lib")
using namespace System;
int main(array<System::String ^> ^args)
{
char ch;
int iRun =1;
int iResult = 0;
WSADATA wsaData;
DWORD nonBlocking =1;
SOCKET RecvSocket;
sockaddr_in RecvAddr;
unsigned short Port = 51234;
char RecvBuf[1024];
int BufLen = 1024;
sockaddr_in SenderAddr;
int SenderAddrSize = sizeof (SenderAddr);
//-----------------------------------------------
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != NO_ERROR) {
wprintf(L"WSAStartup failed with error %d\n", iResult);
return 1;
}
//-----------------------------------------------
// Create a receiver socket to receive datagrams
RecvSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (RecvSocket == INVALID_SOCKET) {
wprintf(L"socket failed with error %d\n", WSAGetLastError());
return 1;
}
// Setting socket to non blocking mode
if(ioctlsocket(RecvSocket, FIONBIO, &nonBlocking)!= 0)
printf("can't Set socket to non blocking mode \n");
//-----------------------------------------------
// Bind the socket to any address and the specified port.
RecvAddr.sin_family = AF_INET;
RecvAddr.sin_port = htons(Port);
RecvAddr.sin_addr.s_addr = htonl(INADDR_ANY);
iResult = bind(RecvSocket, (SOCKADDR *) & RecvAddr, sizeof (RecvAddr));
if (iResult != 0) {
wprintf(L"bind failed with error %d\n", WSAGetLastError());
return 1;
}
//-----------------------------------------------
// Call the recvfrom function to receive datagrams
// on the bound socket.
wprintf(L"Receiving datagrams...\n");
while(iRun) {
iResult = recvfrom(RecvSocket,
RecvBuf, BufLen, 0, (SOCKADDR *) & SenderAddr, &SenderAddrSize);
if (iResult == SOCKET_ERROR) {
wprintf(L"recvfrom failed with error %d\n", WSAGetLastError());
Sleep(10);
}
//wprintf(L"recvfrom Success %d\n", iResult);
//wprintf(L"Received Data %s \n",RecvBuf[BufLen]);
}
//-----------------------------------------------
// Close the socket when finished receiving datagrams
wprintf(L"Finished receiving. Closing socket.\n");
iResult = closesocket(RecvSocket);
if (iResult == SOCKET_ERROR) {
wprintf(L"closesocket failed with error %d\n", WSAGetLastError());
return 1;
}
//-----------------------------------------------
scanf("enter any number to terminate %c",&ch);
// Clean up and exit.
wprintf(L"Exiting.\n");
WSACleanup();
return 0;
//Console::WriteLine(L"Hello World");
//return 0;
}
Can any one please help.
Regards
Mahendra
Did you look it up? Winsock error code 10035 is WSAEWOULDBLOCK. You are in non-blocking mode, and the operation you are attempting cannot be completed, because either your send buffer is full when sending or your receive buffer is empty when receiving.

How to send data via post method to a php file in c++?

I am very new to c++. Recently I am trying to pass some data to a php file in c++ via the post method. I have tried a tutorial from MSDN send Function. The code is as follows:
#ifndef UNICODE
#define UNICODE
#endif
#define WIN32_LEAN_AND_MEAN
#include <winsock2.h>
#include <Ws2tcpip.h>
#include <stdio.h>
#include <conio.h>
// Link with ws2_32.lib
#pragma comment(lib, "Ws2_32.lib")
#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT 27015
int main() {
//----------------------
// Declare and initialize variables.
int iResult;
WSADATA wsaData;
struct hostent *host;
SOCKET ConnectSocket = INVALID_SOCKET;
struct sockaddr_in clientService;
int recvbuflen = DEFAULT_BUFLEN;
char *sendbuf = "Client: sending data test";
char recvbuf[DEFAULT_BUFLEN] = "";
//----------------------
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != NO_ERROR) {
wprintf(L"WSAStartup failed with error: %d\n", iResult);
return 1;
}
//----------------------
// Create a SOCKET for connecting to server
ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ConnectSocket == INVALID_SOCKET) {
wprintf(L"socket failed with error: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
//----------------------
// The sockaddr_in structure specifies the address family,
// IP address, and port of the server to be connected to.
clientService.sin_family = AF_INET;
clientService.sin_addr.s_addr = inet_addr( "127.0.0.1" );
clientService.sin_port = htons( 80 );
//----------------------
// Connect to server.
iResult = connect( ConnectSocket, (SOCKADDR*) &clientService, sizeof(clientService) );
if (iResult == SOCKET_ERROR) {
wprintf(L"connect failed with error: %d\n", WSAGetLastError() );
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
//----------------------
// Send an initial buffer
iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );
if (iResult == SOCKET_ERROR) {
wprintf(L"send failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
printf("Bytes Sent: %d\n", iResult);
// shutdown the connection since no more data will be sent
iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
wprintf(L"shutdown failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
// Receive until the peer closes the connection
do {
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
if ( iResult > 0 )
wprintf(L"Bytes received: %d\n", iResult);
else if ( iResult == 0 )
wprintf(L"Connection closed\n");
else
wprintf(L"recv failed with error: %d\n", WSAGetLastError());
} while( iResult > 0 );
// close the socket
iResult = closesocket(ConnectSocket);
if (iResult == SOCKET_ERROR) {
wprintf(L"close failed with error: %d\n", WSAGetLastError());
WSACleanup();
return 1;
}
WSACleanup();
getch();
}
It sends data to the homepage of localhost but I would like to send data somewhere else in localhost(eg. like 'localhost/test/index.php'). If I change the code from clientService.sin_addr.s_addr = inet_addr( "127.0.0.1" ); to clientService.sin_addr.s_addr = inet_addr( "127.0.0.1/test/index.php" ); then I receive some errors in the exe file. But the program compiles successfully.
Please give me a solution. What should I do now?
You are taking the wrong approach. The low-level socket layer only allows you to connect to a specific server (for example your local http server running on 127.0.0.1 listening on port 80) and send raw data. You need to talk HTTP with that server to really do what you want to do.
I suggest that if you are new to C++, you look at one of the many third-party libraries for C++ which allow you to "talk HTTP" with a http server - for example, libCurl