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.
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've been doing the Winsock tutorials and following it exactly. I can't seem to get either send() or recv() to function properly. I have a basic Server and Client program set up, and the connection is being made, but the Server isn't sending a message to the Client. Using the Telnet client also doesn't receive a response from the server. I'm not really sure what's happening, and all the questions I looked at were not basic or had stuff I couldn't really understand what they were doing.
Server.cpp
#include<WinSock2.h>
#include <io.h>
#include <stdio.h>
#pragma comment(lib, "ws2_32.lib") //winsock library
int main(int argc, char *argv[])
{
WSADATA wsa;
SOCKET s, new_socket;
sockaddr_in server, client;
int c;
char *message;
printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2,2), &wsa) != 0)
{
printf("Failed. Error Code : %d", WSAGetLastError());
return 1;
}
else
printf("Initialised.\n");
//create a socket
if((s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET)
{
printf("Could not create socket : %d", WSAGetLastError());
return 2;
}
else
printf("Socket created.\n");
//prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.S_un.S_addr = INADDR_ANY;
server.sin_port = htons(8888);
//bind the socket
if (bind(s, (sockaddr *)&server, sizeof(server)) == SOCKET_ERROR)
{
printf("Bind failed with error code : &d", WSAGetLastError());
return 3;
}
else
puts("Bind done");
//listen
listen(s, 3);
//accept an incoming connection
puts("Waiting for incoming connections...");
c = sizeof(sockaddr_in);
while (new_socket = accept(s, (sockaddr *)&client, &c) != INVALID_SOCKET)
{
printf("Connect successful...\n");
//reply to the client
message = "Hello Client, I have recieved your connection, but I have to go now, bye!\n";
send(new_socket, message, strlen(message), 0);
puts("Message sent.\n");
}
if (new_socket == INVALID_SOCKET)
{
printf("accept() failed with error code : %d", WSAGetLastError());
return 4;
}
//close the socket
closesocket(s);
WSACleanup();
return 0;
}
Client.cpp
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <Windows.h>
#include <WinSock2.h>
#include <WS2tcpip.h>
#include <IPHlpApi.h>
#include <stdio.h>
#pragma comment(lib, "Ws2_32.lib")
int main(int argc, char *argv[])
{
//intialize variables
WSADATA wsa;
char ip[100] = "192.168.1.117";
SOCKET s;
sockaddr_in server;
char *message, server_reply[75];
int recv_size;
//initialize Winsock
printf("\nInitialising Winsock...\n");
if(WSAStartup(MAKEWORD(2,2), &wsa) != 0)
{
printf("Failed. Error Code : %d", WSAGetLastError());
return 1;
}
printf("Initialised.\n");
//create the socket
if((s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET)
{
printf("Could not create socket : %d", WSAGetLastError());
return 3;
}
printf("Socket created.\n");
server.sin_addr.S_un.S_addr = inet_addr(ip);
server.sin_family = AF_INET;
server.sin_port = htons(8888);
//connect to the server
if (connect(s, (sockaddr *)&server, sizeof(server)) < 0)
{
puts("connect error");
return 4;
}
else
{
printf("Connect successful");
recv_size = recv(s, server_reply, 75, 0);
}
if (recv_size <= 0)
{
puts("recv() failed\n");
}
else
{
//add a NULL terminating character to make it a proper string before printing
server_reply[recv_size] = '\0';
puts(server_reply);
}
getchar();
//close the socket
closesocket(s);
WSACleanup();
return 0;
}
The client also fails to print the "recv() failed" line; it's like it's stuck at the recv() call.
On the server side:
you are not checking the return value of listen() for error.
you are not resetting c on each call to accept(), and you are not calling closesocket() on each client that is accepted.
you are not checking the return value of send() for error.
Try this instead:
#include <WinSock2.h>
#include <stdio.h>
#pragma comment(lib, "ws2_32.lib") //winsock library
int main(int argc, char *argv[])
{
WSADATA wsa;
SOCKET s, new_socket;
sockaddr_in server, client;
int c, res, messagelen;
const char *message;
printf("\nInitializing Winsock...");
res = WSAStartup(MAKEWORD(2,2), &wsa);
if (res != 0)
{
printf("Failed. Error: %d\n", res);
return 1;
}
printf("Initialized.\n");
//create a socket
if((s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET)
{
printf("Could not create socket. Error: %d\n", WSAGetLastError());
return 2;
}
printf("Socket created.\n");
//prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.S_un.S_addr = INADDR_ANY;
server.sin_port = htons(8888);
//bind the socket
if (bind(s, (sockaddr *)&server, sizeof(server)) == SOCKET_ERROR)
{
printf("Bind failed. Error: &d", WSAGetLastError());
return 3;
}
printf("Bind done.\n");
//listen
if (listen(s, 3) == SOCKET_ERROR)
{
printf("Listen failed. Error: &d", WSAGetLastError());
return 4;
}
printf("Listening.\n");
//accept incoming connections
printf("Waiting for incoming connections...\n");
do
{
c = sizeof(sockaddr_in);
new_socket = accept(s, (sockaddr *)&client, &c);
if (new_socket == INVALID_SOCKET)
{
printf("Failed to accept a client. Error: %d\n", WSAGetLastError());
return 5;
}
printf("Client connected...\n");
//reply to the client
message = "Hello Client, I have received your connection, but I have to go now, bye!\n";
messagelen = strlen(message);
do
{
res = send(new_socket, message, messagelen, 0);
if (res == SOCKET_ERROR)
{
printf("Failed to send message. Error: %d\n", WSAGetLastError());
break;
}
message += res;
messagelen -= res;
}
while (messagelen > 0);
if (messagelen == 0)
printf("Message sent.\n");
//close the client socket
closesocket(new_socket);
}
while (true);
//close the server socket
closesocket(s);
WSACleanup();
return 0;
}
On the client side, the only real problem I see is your recv() call has a potential buffer overflow waiting to happen, since you ask it to read 75 bytes, and that is the exact size of your buffer. It just happens that your server is only sending 74 bytes max, but if it ever sent more, you could overflow the buffer when appending the '\0' terminator to it.
So, either:
call recv() with sizeof(server_reply)-1 as the buffer size, to give yourself room for the added terminator:
recv_size = recv(s, server_reply, sizeof(server_reply)-1, 0);
use printf() instead of puts() so you don't need to null-terminate the buffer at all when printing it to the console. You can pass recv_size as a parameter to limit the amount of text being printed:
//server_reply[recv_size] = '\0';
//puts(server_reply);
printf("%.*s", recv_size, server_reply);
From the MSDN documentation on closesocket():
Note To assure that all data is sent and received on a connection, an application should call shutdown before calling closesocket (see Graceful shutdown, linger options, and socket closure for more information). Also note, an FD_CLOSE network event is not posted after closesocket is called.
Basically the data you have sent was still pending when you closed the socket.
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 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 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.