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)...
Related
I'm a beginner and trying to set up a TCP-client for the first time, using winsock. I put together a minimal client using some bits of code I found in examples (see below). It's basically working, i.e. I can receive the server's messages, and sending messages gives the expected results.
However, unless I add a loop which constantly does a receive/send routine (or even just the receive part) the connection is closed immediately after it has been established. Can I do something to keep the connection open and only receive or send something when there is demand for it?
The server is a closed source piece of software, so I have no idea about how it is set up.
#include <winsock2.h>
#include <windows.h>
#include <stdio.h>
int startWinsock(void) {
WSADATA wsa;
return WSAStartup(MAKEWORD(2, 2), &wsa);
}
int main(void) {
long rc;
SOCKET s;
SOCKADDR_IN addr;
printf("Starting Winsock... ");
rc = startWinsock();
if (rc != 0) {
printf("Error: unable to start Winsock, error code: %d\n", rc);
}
else {
printf("done.\n");
}
printf("Creating socket... ");
s = socket(AF_INET, SOCK_STREAM, 0);
if (s == INVALID_SOCKET) {
printf("Error: Unable to create socket, error code: %d\n", WSAGetLastError());
}
else {
printf("done.\n");
}
memset(&addr, 0, sizeof(SOCKADDR_IN));
addr.sin_family = AF_INET;
addr.sin_port = htons(10134);
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
rc = connect(s, (SOCKADDR*)&addr, sizeof(SOCKADDR));
if (rc == SOCKET_ERROR) {
printf("Connection failed, error code: %d\n", WSAGetLastError());
}
else {
printf("Connected to 127.0.0.1.\n");
}
//if I add a loop here, which receives and/or sends stuff constantly, the connection stays established
return 0;
}
Very simple:
Your client tries to connect to the server.
If it succeeds, send a command, and read the response.
Keep receiving and sending until you're "done", then close the socket.
In other words:
You have control over when to close the connection - the socket will stay open until you close it.
Essentially, you're inventing your own custom network protocol
STRONG SUGGESTION:
Review Beej's Guide to Network Programming
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
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.
I have written an simple port scanner code to see the whether the host is available or not by establishing the socket connection .The logic is to check for connection if the connection established is successful then the host is available or else if we get error code as WSACONNREFUSED then the host is present.The socket connection is a blocking one and if there's no host on that ip address the program will be blocked until an timeout occurs . I read a couple of examples on the internet on how to use a non blocking socket but they use read and write to check whether we can write to server side or read from the server side to establish the connection .and for that there should be a server code to accept.Is there a way to modify the existing code for the port scanner using a non blocking socket,as i want the present application to run a bit faster any valuable tips would be useful .
The present code is below .
#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 port[]={80,139};
int wmain()
{
// Initialize Winsock
WSADATA wsaData;
int i=0,flag=0;
char ip[20];
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;
sockaddr_in clientService;
// Create a SOCKET for connecting to server
ConnectSocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if (ConnectSocket == INVALID_SOCKET) {
wprintf(L"socket function failed with error: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
// The sockaddr_in structure specifies the address family,
// IP address, and port of the server to be connected to.
printf("\n Enter the Ip Address : ");
scanf("%s",ip);
clientService.sin_family = AF_INET;
clientService.sin_addr.S_un.S_addr = inet_addr(ip);
for(i=0;i<2;i++)
{
clientService.sin_port = htons((unsigned short)port[i]);
iResult = connect(ConnectSocket, (SOCKADDR *) & clientService, sizeof (clientService));
if((iResult==0)||((iResult=WSAGetLastError())==WSAECONNREFUSED))
{
printf(" %d ",iResult);
printf("\n Port Number : %d",port[i]);
printf("\n Machine Found ");
flag=1;
break;
}
}
if(flag==0)
{
printf("\n Machine not found ");
}
iResult = closesocket(ConnectSocket);
if (iResult == SOCKET_ERROR) {
wprintf(L"closesocket function failed with machine %d error: %ld\n",i, WSAGetLastError());
WSACleanup();
return 1;
}
WSACleanup();
return 0;
}
After doing a non-blocking connect(), the socket will become writable when the connect completes. At that point you should check SO_LASTERROR on the socket to see if the connection has completed successfully.
I've just started learning the basics of sockets (Linux). I tried my hand at a small example, but it doesn't work and I have no idea what's wrong.
I get a "Connection Refused" error message.
Here's my code:
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
int main() {
int c;
c = socket(AF_INET, SOCK_STREAM, 0);
if (c < 0) {
printf("Error in creating socket! %s\n", strerror(errno));
return 1;
}
struct sockaddr_in server;
memset(&server, 0, sizeof(server));
server.sin_port = htons(1234);
server.sin_family = AF_INET;
server.sin_addr.s_addr = inet_addr("127.0.0.1"); //local host
if (connect(c, (struct sockaddr *)&server, sizeof(server)) < 0) {
// Here is my error
printf("Error when connecting! %s\n",strerror(errno));
return 1;
}
while(1) {
char msg[100];
printf("Give message: ");
fgets(msg, sizeof(msg), stdin);
send(c, &msg, sizeof(msg), 0);
char resp[100];
recv(c, &resp, sizeof(resp), 0);
printf("Received: %s\n", resp);
}
close(c);
}
EDIT
Of course ! the error was actually in the server. I simply found it weired that the client sent the message, so I narrowed my view, didn't even bother looking back at the server.
Since the error seems to be also in my server, I might end up asking another question and linking it here
Server was listening to (12345) ...
According to the man page:
ECONNREFUSED
No-one listening on the remote address.
In order to provide a simple remote endpoint that accepts your connection and sends back the received data (echo server), you could try something like this python server (or to use netcat):
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("localhost", 1234))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
conn.sendall(data)
conn.close()
Your Answer is: You program is client and it need a server to connect. nc command create server and your program can connect to it.
[root#mg0008 work]# nc -l 127.0.0.1 1234 &
[1] 25380
[root#mg0008 work]# ./socket
Give message: Hello
Hello
probably no server listening port 1234 in your local host