Is there anything more required in order to communicate a server unix process and a client windows process? After compiling both, i run server and then i run client. However, client fails at connect() with error: 10061.
client (windows application):
#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;
}
// 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;
}
// Message that has to be sent.
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.");
closesocket(ConnectSocket);
WSACleanup();
while(1);
return 0;
}
server (unix application):
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <time.h>
#include <gnu/stubs-64.h>
int main(int argc, char *argv[])
{
int n;
int listenfd = 0, connfd = 0;
struct sockaddr_in serv_addr;
char sendBuff[1025];
listenfd = socket(AF_INET, SOCK_STREAM, 0);
memset(&serv_addr, '0', sizeof(serv_addr));
memset(sendBuff, '0', sizeof(sendBuff));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(27015);
bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
listen(listenfd, 10);
while(1)
{
connfd = accept(listenfd, (struct sockaddr*)NULL, NULL);
n = read(connfd,sendBuff,255);
printf("Here is the message: %s\n",sendBuff);
close(connfd);
sleep(1);
}
}
Client is running on Windows 7, while server on Fedora 19 (VMware). The port was ok when i run client-server windows applications. Also, I have no anti-virus SW installed. Any help would be appreciated.
You are getting a connection refused error because the client is connecting to the client machine, not to the server machine.
In the client code, replace the address 127.0.0.1 with the server's address.
Related
I'm attempting to teach myself some networking programming in C++, but I'm running into some core issues that I can't seem to solve.
I have two programs that are in the same VS project- a client and a server. They don't exchange information, they simply connect and tell me when the connection is established. Here is the client file-
SERVER.CPP
#include "stdafx.h"
using namespace std;
int main()
{
//setting up WSA
WSADATA wsaData;
int WSAcheck = WSAStartup(MAKEWORD(2, 2), &wsaData);
//checking WSA
if (WSAcheck != 0)
{
printf("WSA couldn't start correctly\n");
pause();
exit;
}
//setting up the socket
SOCKET serversock = socket(AF_INET, SOCK_STREAM, 0);
//checking socket's validity
if (serversock == INVALID_SOCKET)
{
printf("Socket isn't valid: %d\n", WSAGetLastError());
pause();
exit;
}
//setting up the sockaddr_in for bind()
sockaddr_in server_sockaddr;
server_sockaddr.sin_family = AF_INET;
server_sockaddr.sin_addr.s_addr = INADDR_ANY;
server_sockaddr.sin_port = htons(25565);
//binding the socket.
int bindcheck = bind(serversock, (struct sockaddr *)&server_sockaddr, sizeof(server_sockaddr));
//checking to see if the bind worked, and calling the error if it doesn't
if (bindcheck != 0)
{
printf("Bind failed: %d\n", WSAGetLastError());
pause();
exit;
}
//setting the socket to listen
int listencheck = listen(serversock, 10);
//checking to make sure the listen command was successful
if (listencheck != 0)
{
printf("Listen failed: %d\n", WSAGetLastError());
pause();
exit;
}
//telling that the socket is being set to listen
printf("Socket is ready to accept connections\n");
//accepting any incoming connections
SOCKET clientsocket = accept(serversock, NULL, NULL);
//checking the socket
if (clientsocket == INVALID_SOCKET)
{
printf("Connecting socket isn't valid or has timed out: %d\n", WSAGetLastError());
pause();
exit;
}
//ending the program
printf("fin\n");
pause();
}
CLIENT.CPP
#include "stdafx.h"
using namespace std;
int main()
{
//setting up WSA
WSADATA wsaData;
int WSAcheck = WSAStartup(MAKEWORD(2, 2), &wsaData);
//checking WSA
if (WSAcheck != 0)
{
printf("WSA couldn't start correctly\n");
pause();
exit;
}
//setting up the socket
SOCKET clientsock = socket(AF_INET, SOCK_STREAM, 0);
//checking socket's validity
if (clientsock == INVALID_SOCKET)
{
printf("Socket isn't valid: %d\n", WSAGetLastError());
pause();
exit;
}
//setting up the struct with the connection info
sockaddr_in serverinfo;
serverinfo.sin_family = AF_INET;
serverinfo.sin_addr.s_addr = INADDR_ANY;
serverinfo.sin_port = htons(25565);
//connecting
printf("Trying to connect\n");
connect(clientsock, (SOCKADDR *)&serverinfo, sizeof(serverinfo));
printf("Passed the connect function\n");
pause();
}
STDAFX.H
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
#pragma once
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
#include <winsock2.h>
#include <Ws2tcpip.h>
#include <Inaddr.h>
#include <string.h>
#include <io.h>
#include <Windef.h>
#include <Ws2tcpip.h>
#include <WinNT.h>
#include <Windows.h>
#include <tchar.h>
void pause(void); //defined in stdafx.cpp
pause is defined as getchar(), to break the code to see what is going on.
The output for the client is -
Trying to connect
Passed the connect function
regardless of whether the server process is running.
The output for the server is
The socket is ready to accept connections
regardless of what I test, I cannot get it to pass that.
What am I doing wrong?
You have an error in the client. This is bad:
serverinfo.sin_addr.s_addr = INADDR_ANY;
Instead of INADDR_ANY you have to write the server IP address, maybe 127.0.0.1 if they run in the same server, in binary format.
Use this function to convert from text IP address to binary IP address:
INT WSAAPI InetPton(
_In_ INT Family,
_In_ PCTSTR pszAddrString,
_Out_ PVOID pAddrBuf
);
https://msdn.microsoft.com/en-us/library/windows/desktop/cc805844(v=vs.85).aspx
The code would be:
if(InetPton(AF_INET, "192.168.0.1", (void*)&serverinfo.sin_addr.s_addr) <= 0)
{
//error
}
I need to build communication between Matlab version 2012 and
Visual Studio version 2013 with UDP protocol.
Matlab Installed Computer will be my Server
Visual Studio 2013 Installed Computer will be my Client
Basic Operation
I have to send continiously text files from MATLAB and received at Visual Studio 2013.
Operating Systems
Matlab OS : Mac OSX 10.10 and Visual Sudio 2013 OS : Windows 10.
I am going to use UDP protocol between them and send integer values from MATLAB to Visual Studio.
I tried this kind of communication, between 2 computers, both of them have Visual Studio installed, and I successfully send bytes between them.
Unfortunately I couldn't establish communication between MATLAB and Visual Studio.
Client Code
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
// Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")
#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "27015"
int __cdecl main(int argc, char **argv)
{
WSADATA wsaData;
SOCKET ConnectSocket = INVALID_SOCKET;
struct addrinfo *result = NULL,
*ptr = NULL,
hints;
char *sendbuf = "(!)Hello, I'm Client Lenovo Z570";
char recvbuf[DEFAULT_BUFLEN];
int iResult;
int recvbuflen = DEFAULT_BUFLEN;
// Validate the parameters
if (argc != 2) {
printf("\n\n\n\t\t\tusage: %s server-name\n\n\n\t\t\t", argv[0]);
system("pause");
return 1;
}
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("\n\n\n\t\t\tWSAStartup failed with error: %d\n\n \n\t\t\t", iResult);
system("pause");
return 1;
}
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
// Resolve the server address and port
iResult = getaddrinfo(argv[1], DEFAULT_PORT, &hints, &result);
if (iResult != 0) {
printf("\n\n\n\t\t\tgetaddrinfo failed with error: %d\n\n\n\t\t\t", iResult);
WSACleanup();
system("pause");
return 1;
}
// Attempt to connect to an address until one succeeds
for (ptr = result; ptr != NULL; ptr = ptr->ai_next) {
// Create a SOCKET for connecting to server
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,
ptr->ai_protocol);
if (ConnectSocket == INVALID_SOCKET) {
printf("\n\n\n\t\t\tsocket failed with error: %ld\n\n\n\t\t\t", WSAGetLastError());
WSACleanup();
system("pause");
return 1;
}
// Connect to server.
iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR) {
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
break;
}
freeaddrinfo(result);
if (ConnectSocket == INVALID_SOCKET) {
printf("\n\n\n\t\t\tUnable to connect to server!\n\n\n\t\t\t");
WSACleanup();
system("pause");
return 1;
}
// Send an initial buffer
iResult = send(ConnectSocket, sendbuf, (int)strlen(sendbuf), 0);
if (iResult == SOCKET_ERROR) {
printf("\n\n\n\t\t\tsend failed with error: %d\n\n\n\t\t\t", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
system("pause");
return 1;
}
printf("\n\n\n\t\t\tBytes Sent: %ld\n\n\n\t\t\t", iResult);
// shutdown the connection since no more data will be sent
iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf("\n\n\n\t\t\tshutdown failed with error: %d\n\n\n\t\t\t", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
system("pause");
return 1;
}
// Receive until the peer closes the connection
do {
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
if (iResult > 0) {
printf("\n\n\n\t\t\tBytes received: %d\n\n\n\t\t\t", iResult);
printf("\n\n\n\t\t\tContent of the Received Packet:\n\n\n\t\t\t ");
for (int i = 0; i < sizeof(recvbuf); i++){
if (isascii(recvbuf[i])){
putchar(recvbuf[i]);
}
}
}
else if (iResult == 0)
printf("\n\n\n\t\t\tConnection closed\n\n\n\t\t\t");
else
printf("\n\n\n\t\t\trecv failed with error: %d\n\n\n\t\t\t", WSAGetLastError());
} while (iResult > 0);
// cleanup
closesocket(ConnectSocket);
WSACleanup();
system("pause");
return 0;
}
About Using Code
I found this code on Microsoft website. Before Launching the code I set up the IP address of Server.
Error
The code gave me the error "Unable to Connect Server!"
Could you please help me?
Any idea will be appreciated. Thanks.
I hope the following example will help anyone, who is willing to learn udp sending. Following Code will work both ethernet and wifi connections.
The code connect to 27015 port of the sender. For example you want to connect 8888 port then change
unsigned short Port = 27015; to unsigned short Port = 8888;
#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")
int main()
{
int iResult = 0;
WSADATA wsaData;
SOCKET RecvSocket;
sockaddr_in RecvAddr;
unsigned short Port = 27015;
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;
}
//-----------------------------------------------
// 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");
iResult = recvfrom(RecvSocket,
RecvBuf, BufLen, 0, (SOCKADDR *) & SenderAddr, &SenderAddrSize);
if (iResult == SOCKET_ERROR) {
wprintf(L"recvfrom failed with error %d\n", WSAGetLastError());
}
//-----------------------------------------------
// 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;
}
//-----------------------------------------------
// Clean up and exit.
wprintf(L"Exiting.\n");
WSACleanup();
return 0;
}
P.S. If you want to connect to the specific IP address change
RecvAddr.sin_addr.s_addr = htonl(INADDR_ANY);
code into for example Assume your IP is 192.168.2.1 then
RecvAddr.sin_addr.s_addr = inet_addr("192.168.2.1");
If you still have question, don't hesitate feel free to ask, If I know it; I will answer it.
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;
}
I am running a server client winsock software to transmit data in a loop from client to server. There is no problem in first transmission and it is perfect.
The second transmission and so on is corrupted and I don't know if it is about keep alive or something else. I spent 2 days trying to figure out.
Server side
#include"stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <winsock2.h>
#include<Windows.h>
#include <time.h>
#include"iostream"
#include"string"
#define MAXLINE 1000
int main()
{
// Initialize Winsock
WSADATA wsaData;
std::string message;
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != NO_ERROR)
printf("Server: Error at WSAStartup().\n");
// Create a SOCKET for listening for incoming connection requests.
SOCKET sockListen;
sockListen = socket(AF_INET, SOCK_STREAM, 0);
if (sockListen == INVALID_SOCKET)
{
printf("Server: Error at socket(): %ld\n", WSAGetLastError());
WSACleanup();
return 0;
}
// The sockaddr_in structure specifies the address family,
// IP address, and port for the socket that is being bound.
struct sockaddr_in servAddr;
memset(&servAddr, 0, sizeof (servAddr));
servAddr.sin_family = AF_INET;
servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
servAddr.sin_port = htons(5000); /* daytime server */
if (bind(sockListen, (SOCKADDR*)&servAddr, sizeof(servAddr)) == SOCKET_ERROR)
{
printf("Server: bind() failed.\n");
closesocket(sockListen);
return 0;
}
// Listen for incoming connection requests on the created socket
if (listen(sockListen, 1) == SOCKET_ERROR)
printf("Server: listen(): Error listening on socket.\n");
printf("Server: I'm listening on socket, waiting for connection...\n");
SOCKET sockConn;
char recvbuff[MAXLINE];
while (1)
{
sockConn = accept(sockListen, NULL, NULL);
recv(sockConn, recvbuff, MAXLINE, 0);
message = recvbuff;
printf("%s \n", message);
std::cout << WSAGetLastError();
Sleep(100);
memset(recvbuff, 0, MAXLINE * (sizeof recvbuff[0]));
}
WSACleanup();
return 0;
}
Client side
#include"stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <winsock2.h>
#include<Windows.h>
#include <time.h>
#include"iostream"
#define MAXLINE 1000
int main()
{
// Initialize Winsock
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != NO_ERROR)
printf("Client: Error at WSAStartup().\n");
// Create a SOCKET to connect to Server.
SOCKET sockClient;
sockClient = socket(AF_INET, SOCK_STREAM, 0);
if (sockClient == INVALID_SOCKET)
{
printf("Client: Error at socket(): %ld\n", WSAGetLastError());
WSACleanup();
return 0;
}
// The sockaddr_in structure specifies the address family,
// IP address, and port for the socket that is being bound.
struct sockaddr_in servAddr;
char servHost[16];
memset(&servAddr, 0, sizeof (servAddr));
printf("Enter Host IP: ");
scanf("%s", servHost);
servAddr.sin_family = AF_INET;
servAddr.sin_addr.s_addr = inet_addr(servHost);
servAddr.sin_port = htons(5000); /* daytime server */
// Connect to a server.
if (connect(sockClient, (SOCKADDR*)&servAddr, sizeof(servAddr)) == SOCKET_ERROR)
{
printf("Client: connect() - Failed to connect.\n");
WSACleanup();
return 0;
}
char buff[MAXLINE];
// Read data from server and display
connect(sockClient, (SOCKADDR*)&servAddr, sizeof(servAddr));
for (int x = 0; x < 100; x++)
{
sprintf(buff, "transmission number %d",x);
send(sockClient, buff, strlen(buff), 0);
memset(buff, 0, MAXLINE * (sizeof buff[0]));
Sleep(3000);
}
closesocket(sockClient);
WSACleanup();
closesocket(sockClient);
return 0;
}
the thing is i don't need to do the loop
sockConn = accept(sockListen, NULL, NULL);
just put it before the server loop solved and the problem solved even that am not sure why
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.