Winsock 10061/10060: Connection to remote server is not successful - c

There are some other questions related to this, but they are not solving my problem. So I am asking so that some other possible solution can be seen.
I am implementing the socket programming. Socket is being successfully created, and it connects successfully to localhost. But when I choose some remote server, then it gives the error 10061 and sometimes 10060. I tried many remote servers(for example: google.com and my company hostname also).
I checked the firewall it is OFF. my code is given below:
/*
Socket Programming on Windows Machine
Author : Raza Javed
Date : 11-10-2022
*/
#include<stdio.h>
#include<winsock2.h>
#include<string.h>
int main(int argc, char *argv[])
{
// Winsock Initialization
WSADATA wsa; // WSADATA is the structure that holds the information about Winsock library
SOCKET s;
struct sockaddr_in server;
struct in_addr **addr_list;
struct hostent *he;
char *hostname = "localhost";
char ip[100];
printf("Initializing Winsock...");
if (WSAStartup(MAKEWORD(2,2),&wsa)!=0)
{
printf("Failed. Error Code : %d", WSAGetLastError()); //WSAGetLastError is used to get more information about what error occured.
return 1;
}
printf("Initialized.\n");
// Socket Creation
if((s = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
{
printf("Could not create the socket: %d", WSAGetLastError());
}
printf("Socket Created.\n");
// Getting IP using "gethostbyname"
if ((he = gethostbyname(hostname)) == NULL)
{
printf("gethostbyname failed : %d", WSAGetLastError());
return 1;
}
addr_list = (struct in_addr **)he -> h_addr_list; // Casting h_addr_list to in_addr
for(int i = 0; addr_list[i] != NULL; i++)
{
strcpy(ip, inet_ntoa(*addr_list[i]));
}
printf("%s resolved to %s\n", hostname, ip);
// Connecting to server
//memset(&server, "\0", sizeof(server));
server.sin_addr.s_addr = inet_addr(ip);
server.sin_family = AF_INET;
server.sin_port = htons(49835);
if (connect(s, (struct sockaddr *)&server, sizeof(server)) < 0)
{
printf("connect error : %d", WSAGetLastError());
getchar();
return 1;
}
puts("connected");
getchar(); // To hold the terminal screen
return 0;
}
Listening port can be seen here:
TCP 127.0.0.1:49835 0.0.0.0:0 LISTENING
In case of localhost, I get the following output:
Initializing Winsock...Initialized.
Socket Created.
localhost resolved to 127.0.0.1
connected
But when I change it to some remote server for example google like below:
char *hostname = "www.google.com";
Then the output is:
Initializing Winsock...Initialized.
Socket Created.
www.google.com resolved to 142.251.209.132
connect error : 10060
Can someone please help in this. I am completely not getting it.

I found the solution myself. maybe it would be helpful for someone else.
The mistake I was doing is that I have been always using the 'wrong port' to connect. To connect to remote server for example www.google.com, the port number will be 80, so the line of the code above will be:
server.sin_port = htons(80);
because it is for HTTP connection.
just by changing the line like above. It is connected now. Results below:
Initializing Winsock...Initialized.
Socket Created.
www.google.com resolved to 142.250.186.100
connected

Related

Another connect() invalid argument C

I am exploring network programming in C.The code is supposed to connect to a server on port 80 send an http request and from the response print on what server is the web page running on, but it runs into Invalid Argument error. The error occurs with error message "[ERR] connecting to target server: Invalid argument" so the error should be somewhere in the connect() function.
rec = connect(sockfd, (struct sockaddr *)&target_addr, sizeof(struct sockaddr) == -1);
if(rec == -1)
fail("[ERR] connecting to target server");
Although I have seen a lot of similar issues, none of the fixes neither worked or applied to this case, strangely this code works as a standalone program when parsing argc[1] instead of char *name, regardless of what the exact string literal is(ip or hostname, experimented with multiple for both). The only difference between the two being that the entire web server function is written in main and passed command-line arguments(working example) while here it is written as a standalone function and called in main where it was tested on a few web page names and IP addresses.
Any help would be appreciated as I feel this might be some simple mistake I overlooked or something I don't understand well enough. Thanks!
int web_server(char *name){
int sockfd, rec;
struct hostent *host_info;
//struct in_addr *address;
struct sockaddr_in target_addr;
unsigned char buffer[4096];
if(is_ip(name)){
target_addr.sin_addr.s_addr = inet_addr(name);
} else if(host_info = gethostbyname(name)){
if(host_info == NULL){
fail("[ERR] looking up hostname!");
}else{
target_addr.sin_addr = *((struct in_addr *) host_info -> h_addr);
}
} else{
fail("[ERR] getting address");
}
target_addr.sin_family = AF_INET;
target_addr.sin_port = htons(80);
memset(&(target_addr.sin_zero), 0, 8);
sockfd = socket(PF_INET, SOCK_STREAM, 0);
if(sockfd == -1){
fail("[ERR] in socket");
}
rec = connect(sockfd, (struct sockaddr *)&target_addr, sizeof(struct sockaddr) == -1);
if(rec == -1)
fail("[ERR] connecting to target server");
send_string(sockfd, "HEAD / HTTP/1.0\r\n\r\n");
while(recv_line(sockfd, buffer)){
if(strncasecmp(buffer, "Server: ", 7) == 0){
printf("The web server for %s is %s\n", name, buffer+8);
}
}
close(sockfd);
printf("Server line not found\n");
exit(1);
}
int main(){
web_server("127.0.0.1");//doesn't work with hostnames either
}

Send string to HDFS via Winsock

I am currently implementing a C program which schould send a test string to the HDFS cluster by using the Winsock2 library.
The HDFS listens on Port 9999 and the IP-Address is 10.32.0.91 (I use this IP-Address to connect to the HDFS shell via Putty). If the HDFS receives something on Port 9999, it automatically writes it into a test file.
So for example: If I send the string "hello" to the port 9999, HDFS will write "hello" into the testfile.
But it seems that my application is having some trouble on sending this string. In the following you can see the code:
#include <stdio.h>
#include <stdlib.h>
// for networking
#include <Windows.h>
#include <winsock2.h>
int startWinsock() {
WSADATA wsa;
return WSAStartup(MAKEWORD(2, 0), &wsa);
}
int main(int argc, char **argv){
// Initialising Winsock
long rc;
rc = startWinsock();
if(rc != 0) {
printf("Error: startWinsock, error code: %d\n", rc);
return EXIT_FAILURE;
} else {
printf("Winsock has started!\n");
}
printf("Initialised.\n");
// Create socket
SOCKET s;
if((s = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
printf("Could not create socket : %d", WSAGetLastError());
}
printf("Socket created.\n");
// Connect to remote server
struct sockaddr_in hdfs_server;
memset(&hdfs_server, 0, sizeof(hdfs_server));
hdfs_server.sin_addr.s_addr = inet_addr("10.32.0.91");
hdfs_server.sin_family = AF_INET;
hdfs_server.sin_port = htons(9999);
// bind socket to local address and port
if((bind(s, (struct sockaddr *)&hdfs_server, sizeof(hdfs_server)) < 0)){
perror("Error:bind failed!");
return EXIT_FAILURE;
}
// send string
char *sendbuf = "Hello";
send(s, sendbuf, (int)strlen(sendbuf), 0);
return 0;
}
When executing this code, I get the following output in the command prompt:
What am I doing wrong here? The IP-address must be correct because I can connect via putty by entering this IP-address. Any suggestions? Any help is highly appreciated!
You are trying to bind your socket locally to an IP address that does not belong to the local machine, that is why you are getting an "invalid argument" error from bind().
Since you are writing a client and not a server, you need to use connect() instead of bind():
// Connect to remote server
struct sockaddr_in hdfs_server;
memset(&hdfs_server, 0, sizeof(hdfs_server));
hdfs_server.sin_addr.s_addr = inet_addr("10.32.0.91");
hdfs_server.sin_family = AF_INET;
hdfs_server.sin_port = htons(9999);
if(connect(s, (struct sockaddr *)&hdfs_server, sizeof(hdfs_server)) < 0){
perror("Error:connect failed!");
return EXIT_FAILURE;
}

C socket programming under windows

Hi I'm new to socket programming and I'm trying out the following code from the tutorial of http://www.binarytides.com/winsock-socket-programming-tutorial/
I'm trying to connect to server and I'm using the IP address of google. Here is the code:
#include<stdio.h>
#include<winsock2.h>
#pragma comment(lib,"ws2_32.lib") //Winsock Library
int main(int argc , char *argv[])
{
WSADATA wsa;
SOCKET s;
struct sockaddr_in server;
printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
{
printf("Failed. Error Code : %d",WSAGetLastError());
return 1;
}
printf("Initialised.\n");
//Create a socket
if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
{
printf("Could not create socket : %d" , WSAGetLastError());
}
printf("Socket created.\n");
server.sin_addr.s_addr = inet_addr("74.125.224.72");
server.sin_family = AF_INET;
server.sin_port = htons(80);
//Connect to remote server
if (connect(s, (struct sockaddr *)&server , sizeof(server)) < 0)
{
puts("connect error");
return 1;
}
puts("Connected");
return 0;
}
So far socket can be created but I can't connect to the server. To be more specific I always exit and have following:
The program '[2060] SocketCTest.exe: Native' has exited with code 1 (0x1).
even if I set a breakpoint before returns.
There's no error. I've tried on my computer and connect returned with error (WSAETIMEDOUT). I'm not sure whether there are the network settings on my computer, proxies, firewalls, and so on; or that google host is configured not to accept direct socket connections.
Anyway here's your code with some small adjustments:
#include <stdio.h>
#include <conio.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib") //Winsock Library
int main(int argc, char *argv[])
{
WSADATA wsa;
SOCKET s;
struct sockaddr_in server;
char c = 0;
printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2,2), &wsa) != 0)
{
printf("Failed. Error Code : %d.\nPress a key to exit...", WSAGetLastError());
c = getch();
return 1;
}
printf("Initialised.\n");
//Create a socket
if((s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET)
{
printf("Could not create socket : %d.\n", WSAGetLastError());
WSACleanup();
c = getch();
return 1;
}
printf("Socket created. Connecting...\n");
memset(&server, 0, sizeof server);
server.sin_addr.s_addr = inet_addr("74.125.224.72");
server.sin_family = AF_INET;
server.sin_port = htons(80);
//Connect to remote server
if (connect(s, (struct sockaddr *)&server, sizeof(server)) < 0)
{
printf("Connect error:%d.\nPress a key to exit...", WSAGetLastError());
closesocket(s);
WSACleanup();
c = getch();
return 1;
}
puts("Connected.\nPress a key to exit...");
closesocket(s);
WSACleanup();
c = getch();
return 0;
}
Now if you want to see the code actually connecting i'd suggest using localhost (127.0.0.1) instead of 74.125.224.72, and the port 3389 for example (it's the Remote Desktop Server (RDP) port, if you have RDP configured and running on your computer) instead of 80; or you could let 80 if you have a web server (IIS?) running on your computer.
To get a list of server programs that run on your computer run the command:
`netstat -an | findstr LISTEN`
which would output a bunch of lines (and the ones that we care about are) in this form (here's the one corresponding to the RDP example from above):
`TCP 127.0.0.1:3389 0.0.0.0:0 LISTENING`

Winsock Error 1013- Permission Denied

I'm trying to run the simple program below using C:
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
#pragma comment (lib, "Ws2_32.lib")
int main(int argc, char **argv)
{
int iResult;
WSADATA wsa;
SOCKET s;
struct sockaddr_in server;
printf("Initialising Winsock...\n");
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
{
printf("Failed. Error Code : %d", WSAGetLastError());
getchar();
return 1;
}
printf("Initialised.\n");
//Create a socket
if ((s = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
{
printf("Could not create socket : %d", WSAGetLastError());
getchar();
}
printf("Socket created.\n");
server.sin_addr.s_addr = inet_addr("74.125.235.20");
server.sin_family = AF_INET;
server.sin_port = htons(80);
//Connect to remote server
iResult = connect(s, (struct sockaddr *)&server, sizeof (server));
if (iResult == SOCKET_ERROR)
{
printf("Connect function failed with error: %ld\n", WSAGetLastError());
iResult = closesocket(s);
if (iResult == SOCKET_ERROR)
printf("closesocket function failed with error: %ld\n", WSAGetLastError());
WSACleanup();
getchar();
return 1;
}
printf("Connected");
getchar();
return 0;
}
This is basically a C program that create a socket and makes a connection to Google. (I'm just following the tutorial: http://www.binarytides.com/winsock-socket-programming-tutorial as I'm completly new to socket programming).
Now my program outputs:
Initialising Winsock...
Initialised.
Socket Created.
Connect function failed with error: 10013
After some research I found that this means that this is a permissions denied error.
I tried looking for some fixes such as running Visual Studio Express as Administrator and running these commands on my command prompt:
netsh winsock reset catalog
netsh int ip reset reset.log hit
and restart my computer but it still does not work.
Its worth mentioning when I ran the 2nd command: netsh int ip reset reset.log hit I got the following error message:
Resetting , failed.
Access is denied.
There's no user specified settings to be reset.
Even though I was running the command prompt as admin.
I also temporarily deactivated my Kaspersky Internet Security but still no fix. I am completely new to C and socket programming.
I've tried your code and I can use it to connect to some other machine. I made a little modification since I do not have a machine running a HTTP server at hand right now. Therefore I used www.google.com:
struct sockaddr_in server;
remoteHost = gethostbyname("www.google.com"); // get IP of www.google.com
server.sin_addr.s_addr = *((unsigned long *)remoteHost->h_addr); // inet_addr("74.125.235.20");
server.sin_family = AF_INET;
server.sin_port = htons(80);
The output of your application is:
Initialising Winsock...
Initialised.
Socket created.
Connected
So basically your implementation is correct.
This means that there is some other gremlin around! The MSDN description of error 10013 is:
WSAEACCES
10013 (0x271D)
An attempt was made to access a socket in a way forbidden by its access permissions.
This can be caused by antivirus or firewall software. Therefore try to disable your firewall and anti virus and run your application again.
If that works try to find the firewall/anti virus setting(s) which may block your application from connecting. This can be quite an ordeal (I know what I'm talking about)...

WinSock program in C, works only on local computer

I'm a newbie in Network Programming, started to learn how to use WinSock in C.
I don't have any knowledge in Networking right now.
Anyway, I've written the following code for Client and Server, using WinSock.
Server:
#include <stdio.h>
#include <stdlib.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#define MY_ERROR 1
#define PORT 7777
#define MAX_NUM_CLIENTS 1 /* I don't know how to thread right now. */
#define MAX_CLIENT_MSG_LEN 1000
int main()
{
WSADATA wsa;
SOCKET mySocket, acceptSocket;
struct sockaddr_in server, client;
int sockAddrInLength = sizeof(struct sockaddr_in);
char clientMessage[MAX_CLIENT_MSG_LEN];
int clientMessageLength;
char* message;
int running = 1;
if(WSAStartup(MAKEWORD(2,2), &wsa) != 0)
{
fprintf(stderr, "WSAStartup failed.\n");
return MY_ERROR;
}
printf("WSAStartup succeded.\n");
mySocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (mySocket == INVALID_SOCKET)
{
fprintf(stderr, "Socket creation failed.\n");
return MY_ERROR;
}
printf("Socket creation succeeded.\n");
server.sin_addr.s_addr = INADDR_ANY;
server.sin_family = AF_INET;
server.sin_port = htons(PORT);
if (bind(mySocket, (struct sockaddr*) &server, sizeof server) == SOCKET_ERROR)
{
fprintf(stderr, "Binding socket on port %d failed.\n", PORT);
return MY_ERROR;
}
printf("Binding socket on port %d successfully.\n", PORT);
while (running)
{
listen(mySocket, MAX_NUM_CLIENTS);
printf("Waiting for a connection...\n");
acceptSocket = accept(mySocket, (struct sockaddr*) &client, &sockAddrInLength);
if (acceptSocket == INVALID_SOCKET)
{
fprintf(stderr, "Accept failed.\n");
return MY_ERROR;
}
printf("Accept succeeded.\n");
if ((clientMessageLength = recv(acceptSocket, clientMessage, sizeof clientMessage, 0)) == SOCKET_ERROR)
{
fprintf(stderr, "Recv failed.\n");
return MY_ERROR;
}
printf("Recv succeeded.\n");
printf("Data:\n");
clientMessage[clientMessageLength] = NULL; /* Null terminator */
printf("Client: %s\n", clientMessage);
message = "Hello client, I'm the server. Bye bye. :-)\n";
if (send(acceptSocket, message, strlen(message), 0) < 0)
{
fprintf(stderr, "Send failed.\n");
return MY_ERROR;
}
printf("Send succeded.\n");
}
closesocket(mySocket);
WSACleanup();
getchar();
return 0;
}
And this is the code for the Client:
#include <stdio.h>
#include <stdlib.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#define IP /* My IP */
#define MY_ERROR 1
#define PORT 7777
#define MAX_SERVER_MSG_LEN 1000
int main()
{
WSADATA wsa;
SOCKET mySocket;
struct sockaddr_in server;
char* message;
char serverMessage[MAX_SERVER_MSG_LEN];
int serverMessageLength;
if(WSAStartup(MAKEWORD(2,2), &wsa) != 0)
{
fprintf(stderr, "WSAStartup failed.\n");
getchar();
return MY_ERROR;
}
printf("WSASucceeded.\n");
mySocket = socket(AF_INET,SOCK_STREAM, IPPROTO_TCP);
if (mySocket == INVALID_SOCKET)
{
fprintf(stderr, "Socket creation failed.\n");
getchar();
return MY_ERROR;
}
server.sin_addr.s_addr = inet_addr(IP);
server.sin_family = AF_INET;
server.sin_port = htons(PORT);
if (connect(mySocket, (struct sockaddr*) &server, sizeof server) < 0)
{
fprintf(stderr, "Connection failed. error: %s\n",WSAGetLastError());
getchar();
return MY_ERROR;
}
printf("Connection established.\n");
message = "Hello server, I'm the sweet client. :-)\n";
if (send(mySocket, message, strlen(message), 0) < 0)
{
fprintf(stderr, "Sending failed.\n");
return MY_ERROR;
}
printf("Sending succeeded.\n");
if ((serverMessageLength = recv(mySocket, serverMessage, sizeof serverMessage, 0)) == SOCKET_ERROR)
{
fprintf(stderr, "Recv failed.\n");
return MY_ERROR;
}
printf("Recv succeeded.\n");
printf("Data:\n");
serverMessage[serverMessageLength] = NULL;
printf("Server: %s", serverMessage);
closesocket(mySocket);
getchar();
return 0;
}
Ok.
When I run both server and client on my comupter, and define IP (in the client code) to be my internal IP (I think, becuase it is the form of 192.168.x.x) it works fine.
When I define IP to be my external IP, it doesn't work on my computer (when I run both program in my computer). The connection failes.
In addition -
When I'm trying to run the client on any other computer, it doesn't work (when IP is defined to be my internal or my external IP), the connection failes.
My questions are:
Why when I run both server & client on my computer, it works just with my internal IP?
What should I do in order that the client could be run on another computer and it will work?
I know that maybe the answer contains terms like "internal/external IPs", "routers", maybe "firewall" or "port forwarding".
Just remember I'm really a newbie in Networking and I don't have any knowledge about those terms, so please: I hope your explnations will be beginner-friendly.
I want to start learning Networking, but my first step is to understand how to use Sockets, and I have a problem in the connetction with other computers.
If you have any articles/something like that in order to give me a better understanding of the problem, it could help too.
Thank you very much! :)
This doesn't look like a coding problem, but a network configuration problem.
Let me try and rephrase what you're saying : Please correct me if I've misunderstood:-
You have an "internal" network (192.168.x.y).
You run the client on one PC on your internal network, and the server on another.
It all works so far.
But, you're also connected to the internet, via a different 'external' IP address
- When your client tries to access the server via this address, it fails. (The exact error code from WSAGetLastError is useful here, please)
At this point, it's down to how you're connected to the net. Let's assume a typical home office scenario. You have broadband, with an ADSL router/modem giving you network connectivity. Now, while the router will have an 'external' IP address, PC's on your local network typically do NOT. So, if you try connecting to the 'external' IP, you're actually trying to talk to the router.
This is where Port forwarding comes into play. You need to configure the router to forward port 7777 to the correct IP address for your server on the internal network. You'll find a screen like this on your router somewhere.
You would enter port 7777 for both 'from' and 'to', enable TCP, and specify the LAN address of your server. The router will then forward incoming connections on port 7777 to the specified server.

Resources