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
}
Related
I am currently a student at Automatics and Applied Informatics. I have a project from Computer Networking, in which I need to make a chat application with the help of threads. Since now I made the receiving part of the connection for the server and made the client, but I get a debug assertion failed error when I run the program. Until now I only have the user connecting part. I really need some help with this because I am stuck.
tcp_server.cpp
#include "winsock2.h"
#include "ClientThread.h"
#include <stdio.h>
#include <string.h>
#include <vector>
#include "ws2tcpip.h"
#pragma comment(lib,"ws2_32.lib")
const unsigned int SysThread::INFINIT_WAIT = UINT_MAX;
void main()
{
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != NO_ERROR) {
printf("Error at WSAStartup()\n");
return;
}
// Socket for listening for incoming requests
SOCKET ListenSocket;
ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ListenSocket == INVALID_SOCKET) {
printf("Error at the listening socket, error code: %d\n", WSAGetLastError);
WSACleanup();
return;
}
int Port = 1300;
char IP[10] = "127.0.0.1";
sockaddr_in ServerAddress;
int ServerLen = sizeof(ServerAddress);
ServerAddress.sin_family = AF_INET;
ServerAddress.sin_port = htons(Port);
inet_pton(AF_INET, IP, &ServerAddress.sin_addr);
if (bind(ListenSocket, (SOCKADDR*)&ServerAddress, sizeof(ServerAddress)) == SOCKET_ERROR) {
printf("bind() failed.\n");
closesocket(ListenSocket);
WSACleanup();
return;
}
if (listen(ListenSocket, 1) == SOCKET_ERROR) {
printf("Error listening on socket.\n");
WSACleanup();
return;
}
std::vector <char*> username;
int RecUserLen = 100;
char RecUser[100];
int ReceiveTheUsername;
// Socket for accepting incoming requests
SOCKET AcceptSocket;
printf("Waiting for client to connect...\n");
while (AcceptSocket = accept(ListenSocket, NULL, NULL)) {
printf("Succesful connection.\n");
int UserNum = 1;
ReceiveTheUsername = recv(AcceptSocket, RecUser, RecUserLen-1, 0);
username[UserNum] = RecUser;
printf("Username: %s", username[UserNum]);
}
}
tcp_client.cpp
#include <iostream>
#include <stdio.h>
#include <string.h>
#include "winsock2.h"
#include "ws2tcpip.h"
#pragma comment(lib, "ws2_32.lib")
void main()
{
int iResult;
//----------------------
WSADATA wsaData;
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != NO_ERROR)
printf("Hiba a WSAStartup() –nál\n");
//----------------------
SOCKET ClientSocket;
ClientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ClientSocket == INVALID_SOCKET)
{
printf("Error at initializing the socket, error code: %ld\n",
WSAGetLastError());
WSACleanup();
return;
}
//---------------------
int Port = 1300;
char IP[10] = "127.0.0.1";
sockaddr_in ServerAddr;
int AddrLen = sizeof(ServerAddr);
ServerAddr.sin_family = AF_INET;
inet_pton(AF_INET, "127.0.0.1", &ServerAddr.sin_addr);
ServerAddr.sin_port = htons(Port);
//----------------------
if (connect(ClientSocket, (SOCKADDR*)&ServerAddr, AddrLen) == SOCKET_ERROR)
{
printf("Connect error, error code: %ld\n",
WSAGetLastError());
WSACleanup();
return;
}
else {
printf("Succesful connection.\n");
}
//----------------------
char UserName[100];
printf("Enter the username: ");
fgets(UserName, 100, stdin);
int SendUsername;
SendUsername = send(ClientSocket, Felhasznalonev, sizeof(Felhasznalonev),0);
if (SendUsername == SOCKET_ERROR) {
printf("Error at sending the username.\n");
closesocket(ClientSocket);
WSACleanup();
return;
}
closesocket(ClientSocket);
WSACleanup();
return;
}
Well there's a clear problem here
std::vector <char*> username;
...
int UserNum = 1;
...
username[UserNum] = RecUser;
username is a zero sized vector, so username[UserNum] is an out of bounds vector access.
Not really sure why you are using a vector at all, it's not adding anything to the code as it currently is. But if you do need to use one then make sure that it is big enough.
The reason for the debug assertion failed error is as John said, you did not set the size of vector <char*> username, so you cannot directly set the value in the vector through assignment.
But the reason why you output garbled characters is that the bytes you read exceed the number of bytes actually returned.
According to the document:
Return value
If no error occurs, recv returns the number of bytes received and the buffer pointed to by the buf parameter will contain this data received. If the connection has been gracefully closed, the return value is zero.
Otherwise, a value of SOCKET_ERROR is returned, and a specific error code can be retrieved by calling
So the return value of the recv function (in the code is ReceiveTheUsername) is actually the number of bytes actually read, not RecUserLen-1, so you can use ReceiveTheUsername to determine the validity of the returned string length.
You only need to initialize the string to be empty like the following code, you can prevent garbled characters.(Of course, you can also manually add '\0' according to the number of characters returned, or intercept the corresponding string according to the character length.)
char RecUser[100] = "";
while (AcceptSocket = accept(ListenSocket, NULL, NULL)) {
printf("Succesful connection.\n");
ReceiveTheUsername = recv(AcceptSocket, RecUser, RecUserLen - 1, 0);
username.push_back(RecUser);
printf("Username: %s", username.back());
}
I'm having issues with my connect() method on the client side of my socket programming. I'm not sure if the issue is with my code or my method of running it. I'm running it in two seperate terminal windows - one for the server (which I'm running first) with the command './server 8080' and one for the client with the command './client 4 8080 hello'. When I run my code, the server program stops in the while loop just after the printf("this prints\n") line. I presume this means that it is waiting for a client to connect to it. The client program fails on the connect() call, and prints out my error message "Connection Failed". My code is posted below.
Server Code:
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#include <sys/wait.h>
#define bufsize 1024
void eatZombies(int n){
wait3(NULL,WNOHANG,NULL); // Nom Nom
}
int main(int argc, char *argv[]){
int sock, length, msgsock, status;
struct sockaddr_in server;
pid_t id;
signal(SIGCHLD, &eatZombies);
int server_fd = socket(AF_INET, SOCK_STREAM, 0);
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(atoi(argv[1])); // this time 1st arg is port#
if(bind(server_fd, (struct sockaddr *)&server, sizeof(server)) < 0){
printf("Error binding the socket\n");
exit(0);
}
if(listen(server_fd, SOMAXCONN) < 0){
printf("Error listening for connections\n");
exit(0);
}
char buffer[1024] = {0};
char *hello = "Hello from server";
int addrlen = sizeof(server);
while(1){
printf("this prints\n");
int client_fd = accept(server_fd, (struct sockaddr *)&server, (socklen_t*)&addrlen);
printf("this doesnt\n");
if(client_fd < 0){
printf("Error accepting connection\n");
exit(0);
}
// the next call makes a new child process that will actually handle the client.
id = fork();
// when id == 0, this is the child and needs to do the work for the server.
// when if > 0, this is the parent, and it should just loop around,
// when id < 0, we had an error.
if(id > 0){
continue;
}
else if(id < 0){
printf("Error\n");
exit(0);
}
read(client_fd, buffer, 1024);
printf("%s\n", buffer);
write(client_fd, hello, strlen(hello), 0);
printf("Hello message sent\n");
exit(0);
}
return 0;
}
Client Code:
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define bufsize 1024
int main(argc, argv) int argc; char *argv[];{
int sock, rval;
struct hostent *host;
struct sockaddr_in server; // not a pointer
char buf[bufsize];
printf("%d\n", argc);
if(argc != 4){
printf("usage:\ntcpclient hostname port string\n\n");
return(-1);
}
// look up hostname (server) using DNS
if ((host = gethostbyname(argv[1])) == 0) {
fprintf(stderr, "%s: unknown host\n", argv[1]);
return(-1);
}
// Set up fields for socket to point to host and port
bcopy(host->h_addr, &server.sin_addr, host->h_length);
server.sin_family = AF_INET;
server.sin_port = htons(atoi(argv[2]));
// Create socket
sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock < 0){
printf("Socket Creation Failed\n");
exit(0);
}
// connect (3-way handshake)
if(connect(sock, (struct sockaddr *)&server, sizeof(server)) < 0){
printf("Connection Failed\n");
exit(0);
}
// Copy the arg into buf so we can send it to the server
strncpy(buf, argv[3], bufsize);
// Send sentence to server
send(sock, buf, strlen(buf), 0);
printf("Message sent\n");
// read response from server
rval = read(sock, buf, bufsize);
// print result to window
fprintf(stdout,"%s\n", buf);
close(sock);
}
When running ./client 4 8080 hello, 4 is the host name. You meant to call ./client localhost 8080 hello.
So it was just a mistake in calling the application, not in the code.
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
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.
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.