UDP client not receiving UDP server message - c

Hai friends I am a newbie learning winsock2. the following is my udp server and client programs.
I this program the client does not know the ip address of the server but knows only the port. But the server broadcasts a message all over the network.
when the client gets the message it traces back the ip of the server and connects to it.
Both my server and client show no error while compiling.
But while Executing the client's recvfrom() statement shows error
the following are the part of my code.
SERVER CODE:
#include "stdafx.h"
#include<stdio.h>
#include<WinSock2.h>
#pragma comment (lib,"ws2_32.lib")
DWORD WINAPI UDPCONN(LPVOID x)
{
SOCKET s=(SOCKET)x;
char bro[200]="I am SERVER";
struct sockaddr_in hum;
hum.sin_family=AF_INET;
hum.sin_addr.s_addr=INADDR_BROADCAST;
hum.sin_port=htons(8888);
while (1)
{
if(sendto(s,bro,sizeof(bro),0,(struct sockaddr *)&hum,sizeof(hum))==SOCKET_ERROR)
{
printf("\nBroadcast failed ERROR CODE : %d\n",WSAGetLastError());
exit(1);
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
SOCKET s;
struct sockaddr_in hum;
int opt=1;
//Initializing winsock2
WSADATA wsa;
if((WSAStartup(MAKEWORD(2,2),&wsa))!=0)
{
printf("\nWinsock Not initialized ERROR CODE : %d\n",WSAGetLastError());
return 1;
}
//UDP Socket Creation
if((s=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP))==INVALID_SOCKET)
{
printf("\nUDP Socket not created ERROR CODE : %d\n",WSAGetLastError());
WSACleanup();
return 1;
}
//socket defenition
hum.sin_family=AF_INET;
hum.sin_addr.s_addr=INADDR_ANY;
hum.sin_port=htons(8888);
//Broadcast permission
if((setsockopt(s,SOL_SOCKET,SO_BROADCAST,(char *)&opt,sizeof(opt)))<0)
{
printf("\nBroadcast permissions failed ERROR CODE : %d\n",WSAGetLastError());
WSACleanup();
return 1;
}
//UDP SOCKET Binding
if((bind(s,(sockaddr *)&hum,sizeof(hum)))==SOCKET_ERROR)
{
printf("\nUDP socket binding failed ERROR CODE :%d\n",WSAGetLastError());
WSACleanup();
return 1;
}
//UDP connection thread
DWORD th;
CreateThread(NULL,0,UDPCONN,(LPVOID)s,0,&th);
CLIENT CODE :
#include "stdafx.h"
#include <stdio.h>
#include <WinSock2.h>
#pragma comment(lib,"ws2_32.lib")
int _tmain(int argc, _TCHAR* argv[])
{
//UDP Data
int slen;
char message[300];
int opt=1;
SOCKET s;
struct sockaddr_in sent;
//Initializing winsock
WSADATA wsa;
if((WSAStartup(MAKEWORD(2,2),&wsa))!=0)
{
printf("\nFailed Initializing Winsock EROR CODE : %d\n",WSAGetLastError());
return 1;
}
//UDP Socket creation
if((s=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP))== SOCKET_ERROR)
{
printf("\nUDP socket creation failed ERROR CODE :%d\n",WSAGetLastError());
WSACleanup();
return 1;
}
//UDP Broadcast permissions
if((setsockopt(s,SOL_SOCKET,SO_BROADCAST,(char *)&opt,sizeof(opt)))<0)
{
printf("\nERROR in broadcasting ERROR CODE : %d \n",WSAGetLastError());
WSACleanup();
return 1;
}
//UDP socket definition
sent.sin_family=AF_INET;
sent.sin_addr.s_addr=INADDR_ANY;
sent.sin_port=htons(8888);
//UDP Receiving broadcasted data
slen=sizeof(sent);
//fflush(stdout);
memset(message,'\0',300);
if((recvfrom(s,message,sizeof(message),0,(struct sockaddr *)&sent,&slen))<0)
{
printf("\nUDP Broadcast not received ERROR CODE : %d\n",WSAGetLastError());
WSACleanup();
return 1;
}
puts("\nGot server broadcast\n");
puts("\nTracing server ip\n");
getpeername(s,(sockaddr *)&sent,&slen);
...
}
Here my client throw an error
UDP Broadcast not received ERROR CODE : 10022
Description of the error code 10022 : Invalid argument.
Some invalid argument was supplied (for example, specifying an invalid level to the setsockopt function). In some instances, it also refers to the current state of the socket—for instance, calling accept on a socket that is not listening.
According to the error description one of the arguments in the recvfrom() function is invalid. But i could not find out the invalid argument .
Please help me clear the error.

If you read the recvfrom() documentation, it tells you exactly why you are getting the error in your client code:
Parameters
s [in]
A descriptor identifying a bound socket.
...
WSAEINVAL
The socket has not been bound with bind, or an unknown flag was specified, or MSG_OOB was specified for a socket with SO_OOBINLINE enabled, or (for byte stream-style sockets only) len was zero or negative.
You are not calling bind() on the socket before calling recvfrom(). More importantly, you cannot bind() the client and server to the same IP/port when they are running on the same machine. Change the port that you broadcast to, and then have the client bind to that port.
Also, the last two parameters of recvfrom() provide you with the IP/Port of the datagram sender. They are not for specifying the network adapter to read datagrams on. You do not need to use getpeername() in this situation.
There are some other issues with your code:
On the client side, socket() returns INVALID_SOCKET on failure, not SOCKET_ERROR.
On the server side, you really should not be using INADDR_BROADCAST. You should bind() the server socket to a specific network adapter and then sendto() its particular subnet broadcast IP, which you can calculate using GetAdaptersInfo() or GetAdaptersAddresses().
And on both sides, you cannot use WSAGetLastError() if WSAStartup() fails, that is why WSAStartup() returns the error code directly. And you are not closing the sockets before calling WSACleanup();
Try this:
SERVER CODE:
#include "stdafx.h"
#include <stdio.h>
#include <WinSock2.h>
#pragma comment (lib,"ws2_32.lib")
DWORD WINAPI UDPCONN(LPVOID x)
{
SOCKET s = (SOCKET)x;
char bro[200] = "I am SERVER";
struct sockaddr_in hum;
memset(&hum, 0, sizeof(addr));
hum.sin_family = AF_INET;
hum.sin_addr.s_addr = INADDR_BROADCAST; // TODO: replace with subnet broadcast IP
hum.sin_port = htons(8887);
while (1)
{
if (sendto(s, bro, sizeof(bro), 0, (struct sockaddr *)&hum, sizeof(hum)) == SOCKET_ERROR)
{
printf("\nBroadcast failed ERROR CODE : %d\n", WSAGetLastError());
return 1;
}
}
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
SOCKET s;
struct sockaddr_in hum;
int err, opt=1;
//Initializing winsock2
WSADATA wsa;
err = WSAStartup(MAKEWORD(2,2), &wsa);
if (err != 0)
{
printf("\nWinsock Not initialized ERROR CODE : %d\n", err);
return 1;
}
//UDP Socket Creation
s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (s == INVALID_SOCKET)
{
printf("\nUDP Socket not created ERROR CODE : %d\n", WSAGetLastError());
WSACleanup();
return 1;
}
//socket defenition
memset(&hum, 0, sizeof(hum));
hum.sin_family = AF_INET;
hum.sin_addr.s_addr = INADDR_ANY; // TODO: replace with a specific NIC IP
hum.sin_port = htons(8888);
//Broadcast permission
if (setsockopt(s, SOL_SOCKET, SO_BROADCAST, (char *)&opt, sizeof(opt)) == SOCKET_ERROR)
{
printf("\nBroadcast permissions failed ERROR CODE : %d\n", WSAGetLastError());
closesocket(s);
WSACleanup();
return 1;
}
//UDP SOCKET Binding
if (bind(s, (sockaddr *)&hum, sizeof(hum)) == SOCKET_ERROR)
{
printf("\nUDP socket binding failed ERROR CODE : %d\n", WSAGetLastError());
closesocket(s);
WSACleanup();
return 1;
}
//UDP connection thread
DWORD th;
HANDLE hThread = CreateThread(NULL,0, UDPCONN, s, 0, &th);
if (!hThread)
{
printf("\nUDP thread failed ERROR CODE : %u\n", GetLastError());
closesocket(s);
WSACleanup();
return 1;
}
// do other things, wait for thread to terminate ...
DWORD exitCode = 0;
GetExitCodeThread(hThread, &exitCode);
CloseHandle(hThread);
closesocket(s);
WSACleanup();
return exitCode;
}
CLIENT CODE :
#include "stdafx.h"
#include <stdio.h>
#include <WinSock2.h>
#pragma comment(lib,"ws2_32.lib")
int _tmain(int argc, _TCHAR* argv[])
{
//UDP Data
int addrlen, msglen;
char message[300];
int err, opt=1;
SOCKET s;
struct sockaddr_in hum, addr;
//Initializing winsock
WSADATA wsa;
err = WSAStartup(MAKEWORD(2,2), &wsa);
if (err != 0)
{
printf("\nFailed Initializing Winsock EROR CODE : %d\n", err);
return 1;
}
//UDP Socket creation
s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (s == INVALID_SOCKET)
{
printf("\nUDP socket creation failed ERROR CODE : %d\n", WSAGetLastError());
closesocket(s);
WSACleanup();
return 1;
}
//UDP Broadcast permissions
if (setsockopt(s, SOL_SOCKET, SO_BROADCAST, (char *)&opt, sizeof(opt)) == SOCKET_ERROR)
{
printf("\nERROR in broadcasting ERROR CODE : %d \n", WSAGetLastError());
closesocket(s);
WSACleanup();
return 1;
}
//UDP socket definition
memset(&hum, 0, sizeof(addr));
hum.sin_family = AF_INET;
hum.sin_addr.s_addr = INADDR_ANY;
hum.sin_port = htons(8887);
//UDP SOCKET Binding
if (bind(s, (sockaddr *)&hum, sizeof(hum)) == SOCKET_ERROR)
{
printf("\nUDP socket binding failed ERROR CODE : %d\n", WSAGetLastError());
closesocket(s);
WSACleanup();
return 1;
}
//UDP Receiving broadcasted data
addrlen = sizeof(addr);
msglen = recvfrom(s, message, sizeof(message), 0, (struct sockaddr *)&addr, &addrlen);
if (msglen == SOCKET_ERROR)
{
printf("\nUDP Broadcast not received ERROR CODE : %d\n", WSAGetLastError());
closesocket(s);
WSACleanup();
return 1;
}
printf("\nGot server broadcast\n");
printf("\nServer ip: %s, port: %hu\n", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
printf("\nMessage: %.*s\n", msglen, message);
...
}

Whatever method i tried sending a broadcast from server and receiving the broadcast from client is not working efficiently.
Instead i done the reverse i.e send a broadcast from client to search for the server is working perfectly.
Here is my modified code.
SERVER CODE:
#include "stdafx.h"
#include<stdio.h>
#include<WinSock2.h>
#pragma comment (lib,"ws2_32.lib")
DWORD WINAPI UDPCONN(LPVOID x)
{
SOCKET s=(SOCKET)x;
struct sockaddr_in server;
int len;
char buf[500]=("I am server");
char message[500];
len=sizeof(server);
int opt=1;
if((s=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP))==INVALID_SOCKET)
{
printf("\nSocket creation failed. ERROR CODE : %d\n",WSAGetLastError());
WSACleanup();
ExitThread(NULL);
}
server.sin_family=AF_INET;
server.sin_addr.s_addr=INADDR_ANY;
server.sin_port=htons(8888);
if(setsockopt(s,SOL_SOCKET,SO_BROADCAST,(char *)&opt,sizeof(opt))<0)
{
printf("\nSetting broadcast failed : %d\n",WSAGetLastError());
WSACleanup();
ExitThread(NULL);
}
if((bind(s,(sockaddr *)&server,sizeof(server)))==SOCKET_ERROR)
{
printf("\nBind failed. ERROR CODE : %d\n",WSAGetLastError());
WSACleanup();
ExitThread(NULL);
}
while(1)
{
fflush(stdout);
memset(message,'\0', 500);
//try to receive some data, this is a blocking call
if (recvfrom(s, message, 500, 0, (struct sockaddr *) &server,&len) == SOCKET_ERROR)
{
printf("recvfrom() failed with error code : %d" , WSAGetLastError());
ExitThread(NULL);
}
if(sendto(s,buf,sizeof(buf),0,(struct sockaddr *)&server,sizeof(server))==SOCKET_ERROR)
{
printf("\nIP Broadcast failed ERROR code : %d\n",WSAGetLastError());
WSACleanup();
ExitThread(NULL);
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
SOCKET s;
//struct sockaddr_in hum;
int opt=1;
//Initializing winsock2
WSADATA wsa;
if((WSAStartup(MAKEWORD(2,2),&wsa))!=0)
{
printf("\nWinsock Not initialized ERROR CODE : %d\n",WSAGetLastError());
return 1;
}
s=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
//UDP connection thread
DWORD th;
CreateThread(NULL,0,UDPCONN,(LPVOID)s,0,&th);
closesocket(s);
CLIENT CODE :
#include "stdafx.h"
#include <stdio.h>
#include <WinSock2.h>
#pragma comment(lib,"ws2_32.lib")
int _tmain(int argc, _TCHAR* argv[])
{
//UDP Data
int slen;
char message[600];
char buf[300]=("Hai server");
int opt=1;
SOCKET s;
struct sockaddr_in sent;
//TCP Connection data
SOCKET t;
struct sockaddr_in server;
char messag[300],server_reply[300];
int recv_size;
//Initializing winsock
WSADATA wsa;
if((WSAStartup(MAKEWORD(2,2),&wsa))!=0)
{
printf("\nFailed Initializing Winsock EROR CODE : %d\n",WSAGetLastError());
return 1;
}
//UDP Socket creation
if((s=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP))== INVALID_SOCKET)
{
printf("\nUDP socket creation failed ERROR CODE :%d\n",WSAGetLastError());
WSACleanup();
return 1;
}
//UDP Broadcast permissions
if((setsockopt(s,SOL_SOCKET,SO_BROADCAST,(char *)&opt,sizeof(opt)))<0)
{
printf("\nERROR in broadcasting ERROR CODE : %d \n",WSAGetLastError());
WSACleanup();
return 1;
}
//UDP socket definition
sent.sin_family=AF_INET;
sent.sin_addr.s_addr=INADDR_BROADCAST;
sent.sin_port=htons(8888);
if (sendto(s, buf, sizeof(buf) , 0 , (struct sockaddr *) &sent,sizeof(sent)) == SOCKET_ERROR)
{
printf("sendto() failed with error code : %d" , WSAGetLastError());
exit(EXIT_FAILURE);
}
//UDP Receiving broadcasted data
slen=sizeof(sent);
fflush(stdout);
memset(message,'\0',300);
if((recvfrom(s,message,sizeof(message),0,(struct sockaddr *)&sent,&slen))<0)
{
printf("\nUDP Broadcast not received ERROR CODE : %d\n",WSAGetLastError());
WSACleanup();
return 1;
}
puts("\nGot server broadcast\n");
puts("\nTracing server ip\n");
getpeername(s,(sockaddr *)&sent,&slen);
closesocket(s);
Both the codes here works perfectly fine in visual studios 2012.
Also this is just one part of my whole big program. But still this part works perfectly fine independently.
So please make sure you compiled and run the program before posting negative comments.

Related

bind() returns error code 10038 using winsock.h

I am trying to implement a client-server architecture using sockets in Windows with winsock.h. When I call bind() function I get the error code 10038 and I don`t know why.
Here it is my code. This is only the server, created inside a thread where I initialice the socket and jump into an infinite loop to read data from client usng recvfrom function.
typedef struct
{
int sockfd;
struct sockaddr_in dir_client;
int long_dir_client;
struct sockaddr_in dir_server;
uint32_t receive_data;
}server_t;
void RX_thread_Client(void)
{
WSADATA wsaData;
server_t server;
int iResult;
int BytesReceived;
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("[RxThreadClient] WSAStartup failed with error: %d\n", iResult);
return;
}
memset((char*)& server.dir_server, 0, sizeof(server.dir_server));
server.dir_server.sin_family = AF_INET;
server.dir_server.sin_addr.s_addr = inet_addr("10.128.169.46");
server.dir_server.sin_port = htons(6500);
server.long_dir_client = sizeof(server.dir_client);
// Create a new socket to make a client connection.
// AF_INET = 2, The Internet Protocol version 4 (IPv4) address family, TCP protocol
if ( server.sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP) == INVALID_SOCKET)
{
printf("[RxThreadClient] Client: socket() failed! Error code: %ld\n", WSAGetLastError());
// Do the clean up
WSACleanup();
// Exit with error
return;
}
else
printf("[RxThreadClient] Client: socket() is OK!\n");
if ( bind(server.sockfd, (struct sockaddr*)&server.dir_server, sizeof(server.dir_server)) < 0) // ERROR IS HERE!!!
{
printf("[RxThreadClient] bind() failed! Error code: %ld\n", WSAGetLastError());
return;
}
else
printf("[RxThreadClient] Client: bind() is OK!\n");
while (1)
{
BytesReceived = recvfrom (server.sockfd, (char*)&server.receive_data,
sizeof(server.receive_data), 0,
(struct sockaddr*) & server.dir_client,
&server.long_dir_client);
if (BytesReceived == SOCKET_ERROR)
{
printf("[RxThreadClient] Client: send() error %ld.\n", WSAGetLastError());
break;
}
else
{
printf("[RxThreadClient] Client: send() is OK - bytes received: %ld\n", BytesReceived);
printf("[RxThreadClient] Word received: %d\n", server.receive_data);
}
Sleep(1000);
}
}
Thank you very much

Error 10038 (Socket operation on invalid socket) when trying to send a string from Winsock2 C program

I'm trying to make a C library that mimics Python socket library.
When i run my main function, an error occurs on simplesend(sucket, "foo");
the whole main function:
int main(){
struct SIMPLESOCKET sucket;
simpleinit(sucket);
simpleconnect(sucket, "ip", "port");
simplesend(sucket, "foo");
simpleclose(sucket);
return 0;
}
this is the definition of the SIMPLESOCKET struct:
#include <winsock2.h>
#include <ws2tcpip.h>
struct SIMPLESOCKET{
WSADATA wsaData;
int iResult;
struct addrinfo *result;
struct addrinfo *ptr;
struct addrinfo hints;
SOCKET ConnectSocket;
};
I get error 10038, which is "socket operation on invalid socket". But when i check s.ConnectSocket, it isn't equal to INVALID_SOCKET.
the simplesend function body:
int simplesend(struct SIMPLESOCKET s, char* msg){
s.iResult = send(s.ConnectSocket, msg, (int) strlen(msg), 0);
if (s.iResult == SOCKET_ERROR) {
printf("send failed: %d\n", WSAGetLastError());
closesocket(s.ConnectSocket);
WSACleanup();
return 1;
}
}
and the only part of the code that does stuff to s.ConnectSocket doesnt give any errors, here it is:
int simpleconnect(struct SIMPLESOCKET s, char* ip, char* port){
memset(&s.hints, 0, sizeof(s.hints));
s.iResult = getaddrinfo(ip, port, &s.hints, &s.result);
if (s.iResult != 0) {
printf("getaddrinfo failed: %d\n", s.iResult);
WSACleanup();
return 1;
}
s.ConnectSocket = INVALID_SOCKET;
s.ptr=s.result;
s.ConnectSocket = socket(s.ptr->ai_family, s.ptr->ai_socktype, s.ptr->ai_protocol);
if (s.ConnectSocket == INVALID_SOCKET) {
printf("Error at socket(): %ld\n", WSAGetLastError());
freeaddrinfo(s.result);
WSACleanup();
return 1;
}
//connect
s.iResult = connect(s.ConnectSocket, s.ptr->ai_addr, (int)s.ptr->ai_addrlen);
if (s.iResult == SOCKET_ERROR) {
printf("1977\n");
closesocket(s.ConnectSocket);
s.ConnectSocket = INVALID_SOCKET;
}
freeaddrinfo(s.result);
if (s.ConnectSocket == INVALID_SOCKET) {
printf("unable to connect to server\n");
WSACleanup();
return 1;
}
}
So, i really don't understand why i get an invalid socket error since i even get the successfull connection on my python server.

udp data not recieved in windows socket program

I am new to windows socket programming. I have a device which gives udp data through a port, ipv6 protocol based. I am trying to capture this in a console application written in visual studio in Windows 7. Socket creation and bind are successful but nothing is recieved from the port specified.
I have done this in Linux since i am basically a linux system software developer and it is working perfect. Is there anything else i need to do to get UDP packets in windows. I have checked with wireshark in windows and found that the UDP packets are coming from the device to the PC.
Working Code Done in Linux:
int main()
{
struct sockaddr_in6 ipv6_addr;
int addrlen, ipv6_sockfd, cnt, err;
char response[200], cmd[500];
cJSON *param, *root;
memset(response, 0, sizeof(response));
ipv6_sockfd = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP);
if (ipv6_sockfd < 0) {
perror("socket");
exit(1);
}
bzero((char *)&ipv6_addr, sizeof(ipv6_addr));
ipv6_addr.sin6_family = AF_INET6;
ipv6_addr.sin6_addr = in6addr_any;
ipv6_addr.sin6_port = htons(DISCOVERY_PORT);
addrlen = sizeof(ipv6_addr);
if (bind(ipv6_sockfd, (struct sockaddr *)&ipv6_addr, sizeof(ipv6_addr)) < 0) {
perror("bind");
exit(1);
}
cnt = recvfrom(ipv6_sockfd, response, sizeof(response), 0, (struct sockaddr *)&ipv6_addr, &addrlen);
if (cnt < 0) {
perror("recvfrom");
exit(1);
}
DBG("Response = \"%s\"\n", response);
close(ipv6_sockfd);
}
Code in Windows:
#include "stdafx.h"
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#define DISCOVERY_PORT 13006
#define DEFAULT_BUFLEN 512
#include <WinSock2.h>
#pragma comment(lib,"ws2_32.lib")
int _tmain(int argc, _TCHAR* argv[])
{
//UDP Data
int addrlen, msglen;
char message[300];
int err, opt = 1;
SOCKET s;
struct sockaddr_in6 hum, addr;
//Initializing winsock
WSADATA wsa;
err = WSAStartup(MAKEWORD(2, 2), &wsa);
if (err != 0)
{
printf("\nFailed Initializing Winsock EROR CODE : %d\n", err);
return 1;
}
//UDP Socket creation
s = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP);
if (s == INVALID_SOCKET)
{
printf("\nUDP socket creation failed ERROR CODE : %d\n", WSAGetLastError());
closesocket(s);
WSACleanup();
return 1;
}
//UDP socket definition
memset(&hum, 0, sizeof(addr));
hum.sin6_family = AF_INET6;
hum.sin6_addr = in6addr_any;
hum.sin6_port = htons(DISCOVERY_PORT);
//UDP SOCKET Binding
if (bind(s, (sockaddr *)&hum, sizeof(hum)) == SOCKET_ERROR)
{
printf("\nUDP socket binding failed ERROR CODE : %d\n", WSAGetLastError());
closesocket(s);
WSACleanup();
return 1;
}
//UDP Receiving data
addrlen = sizeof(addr);
msglen = recvfrom(s, message, sizeof(message), 0, (struct sockaddr *)&addr, &addrlen);
if (msglen == SOCKET_ERROR)
{
printf("\nUDP Broadcast not received ERROR CODE : %d\n", WSAGetLastError());
closesocket(s);
WSACleanup();
return 1;
}
printf("\nMessage: %s\n", message);
return 0;
}
I've implemented a client-server connection over the udp protocol (for handling mouse and keyboard input from smartphone), the only difference is that I used ipv4 instead. Same thing - it perfectly worked on linux, but on windows I didn't see any incoming packet.
The thing that worked to me was to run the program as Administrator and also manually add it to firewall's permissions. In general this wasn't stable on some windows PC's, but after installing my server part program to C:\Program Files it has started to work more or less ok.

WSA Connection refused even though the host is not present

I'm writing a code to discover the devices on the network and this is just a part of it.
I'm trying to discover a host by establishing an socket connection with the host on port 80.
It connects well on some of the hosts on port 80 as the devices are listening on port 80. At times the connect function returns error as WSACONNECTIONREFUSED as there is no web service running on the host.
It is surprising to see that when i try to establish an socket connection on invalid ip addresses I get WSACONNECTIONREFUSED instead of WSAETIMEDOUT.
I googled and found out that the antivirus and firewall can cause the problems and i have disabled both on the scanning machine but no luck what could be causing the problem?
I have posted the code below:
#ifndef UNICODE
#define UNICODE
#endif
#define WIN32_LEAN_AND_MEAN
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#pragma comment(lib, "ws2_32.lib")
int main()
{
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;
}
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;
}
sockaddr_in clientService;
clientService.sin_family = AF_INET;
clientService.sin_addr.s_addr = inet_addr("192.168.4.28"); //No Host by this ip address
clientService.sin_port = htons(80); //Port is 80
iResult = connect(ConnectSocket, (SOCKADDR *) &clientService,
sizeof(clientService));
printf("The socket connect return status : %d ", iResult);
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)
{
printf("\n socket Connection failed ");
WSACleanup();
return 1;
}
WSACleanup();
return 0;
}

socket connection always successful

I'm beginner in winsock programming and i witnessed a peculiar behaviour of the connect function to establish a socket connection.The socket function succeeds even though there's no valid host in the network .For example there's no host with the ip 192.168.4.28 in our network but the connection to the call still succeeds and i tried giving ip address that's outside our network for example 1.1.1.1 and it still succeeded . Is there a reason or there's a bug in the api.i have used the code in the msdn site provided in this
http://msdn.microsoft.com/en-us/library/windows/desktop/ms737625(v=vs.85).aspx .
CODE
#ifndef UNICODE
#define UNICODE
#endif
#define WIN32_LEAN_AND_MEAN
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#pragma comment(lib, "ws2_32.lib")
int main()
{
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;
}
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;
}
sockaddr_in clientService;
clientService.sin_family = AF_INET;
clientService.sin_addr.s_addr = inet_addr("192.168.4.28"); //No Host by this ip address
clientService.sin_port = htons(80); //Port is 80
iResult = connect(ConnectSocket, (SOCKADDR *) & clientService, sizeof (clientService));
printf("The socket connect return status : %d ",iResult); // always 0 , indicating success
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) {
printf("\n socket Connection failed ");
WSACleanup();
return 1;
}
WSACleanup();
return 0;
}

Resources