I'm trying to run server client on my 2 computers in my local network at home.
The first computer is server and the second is client.
I have error 10061 when I'm trying to connect the server. ("error - connect failed. sockfd is 164, errno is 34, WSA is 10061").
error 10061 means -"connection refused. No connection could be made because the target machine actively refused it. This usually results from trying to connect to a service that is inactive on the foreign host — that is, one with no server application running."
I thought it might be firewall problem so I approved in my firewall the port Im using, but stil it doesnt work.
Also, both computer have the same IP(why is that?).
Here's my code:
server.c:
#include <sys/types.h>
#include <signal.h>
#include <fcntl.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <winsock2.h>
#include <windows.h>
#include <tchar.h>
int socketBind(int sockfd, int port){
struct sockaddr_in serv_addr;
ZeroMemory((char*) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(port);
if ( bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0 ){
// we can check errno for exact ERROR
printf("bind failed with errno %d\n",errno);fflush(NULL);
return ERROR;
}
if ( listen(sockfd, 100) == -1 ){
return ERROR;
}
return 1;
}
int main()
{
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2,2), &wsaData) == SOCKET_ERROR) {
printf ("Error initialising WSA.\n");
return -1;
}
int sockfd; // server's listening socket's descriptor id
int port = 4997;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
while ( sockfd < 0 ){ // ERROR
printf("Listener socket creation failed with:%d, errno is %d\n",sockfd,errno);fflush(NULL);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
}
if ( socketBind(sockfd, port) == ERROR ){
printf("Socket bind failed with errno=%d\n",errno);fflush(NULL);
close(sockfd);
return ERROR;
}
printf("Starting to listen to other USERS!\n");fflush(NULL);
struct sockaddr_in cli_addr;
int clilen = sizeof(cli_addr); // length of address
// accept() returns the socket that will be used for Control Connection with the accepted client
printf("*************Waiting for other USERS************\n");fflush(NULL);
int newsockfd = accept(sockfd, (struct sockaddr *)&cli_addr, &clilen);
int readLength;
char command[(128+1)];
while(1)
{
ZeroMemory(command, sizeof(command));
readLength = read(newsockfd, command, 128+1);
if(readLength <= 0)
{
continue;
}
if(readLength > 0)
{
printf(" here should be API's func to command %s", command);fflush(NULL);
}
else
{
close(sockfd);
close(newsockfd);
WSACleanup();
printf("Read failed with errno:%d\n",errno);fflush(NULL);
return ERROR;
}
}
close(sockfd);
close(newsockfd);
WSACleanup();
return 1;
}
client.c:
#include <sys/types.h>
#include <signal.h>
#include <fcntl.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <winsock2.h>
#include <windows.h>
#include <tchar.h>
int verifyWrite(int sockfd, char* command){
int size = strlen(command);
int i=0, x=0;
for(i=0;i<size;){
x = write(sockfd, command, size);
if(x < 0){
return ERROR;
}
if(x >= 0) {
i += x;
}
}
return 0;
}
int sendToAll(char* message, int sockfd)
{
if ( verifyWrite(sockfd, message) < 0 )
{
printf("error while sending message\n");fflush(NULL);
}
return 0;
}
int main()
{
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2,2), &wsaData) == SOCKET_ERROR) {
printf ("Error initialising WSA.\n");
return -1;
}
int port,sockfd;
struct sockaddr_in serv_addr;
sockfd = socket(AF_INET, SOCK_STREAM, 0); //creating control connection
while(sockfd < 0){
printf("error - sockfd = %d\n",sockfd);fflush(NULL);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
}
port = 4997;
ZeroMemory((char*)&serv_addr, sizeof(serv_addr));
serv_addr.sin_addr.s_addr = inet_addr("192.168.1.20");
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(port);
while(connect(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr)) < 0){
printf("error - connect failed. sockfd is %d, errno is %d, WSA is %d\n",sockfd,errno,WSAGetLastError());fflush(NULL);
}
printf("\n opened connection to %s\n", "192.168.1.20");fflush(NULL);
int i = 0;
while(i< 6)
{
sendToAll("just a message", sockfd);
i++;
}
WSACleanup();
return 0;
}
Your server is listening on port 4997, but your client is connecting to port 80 instead. You would have caught that if you had included the listening and connecting IP:Port pairs in your debug output to the console.
Related
I'm working on a client / server program using sockets. The server just listen for connections and prints it's username. The client tries to find the server and sends it's username. When you run the client, you have to pass three arguments: Your username, the IP address and the port.
The program works fine on same computer, but when I try to connect on a different PC, it can't connect. After a while, it prints "Error connecting to host.".
I am doing something wrong?
Thanks!
Edit: Just one more info. My desktop (server) is on tethed USB internet connection, provided from my smartphone. The client is on Wi-Fi.
Edit2: Now the desktop is on cable and the notebook (client) is on Wi-Fi. Internet conection is up on both devices. I still can't connect. Connection timeout is the error.
Edit3: Well, now I connected both devices on wired (same router) and I connected fine. Seems I have to send an email to IT department of my uni.
client.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#define PORT 4000
#define WORD_SIZE 256
int main(int argc, char * argv[]) {
pthread_t tid;
int sockfd;
struct sockaddr_in serv_addr;
struct hostent * server;
if (argc != 4)
{
printf("Not enough arguments, please inform:\n");
printf("<username> <server_ip_adress> <port>");
return -1;
}
char username[WORD_SIZE], server_ip[WORD_SIZE], port[WORD_SIZE];
strcpy(username, argv[1]);
strcpy(server_ip, argv[2]);
strcpy(port, argv[3]);
server = gethostbyname(server_ip);
if (server == NULL)
{
printf("Error: no such host\n");
return -1;
}
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
printf("Error opening socket\n");
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
serv_addr.sin_addr = * ((struct in_addr * ) server->h_addr);
bzero( & (serv_addr.sin_zero), 8);
int status = connect(sockfd, (struct sockaddr * ) & serv_addr, sizeof(serv_addr));
if (status < 0)
{
printf("Error connecting to host.\n");
return -1;
}
if (send(sockfd, username, WORD_SIZE, 0) < 0)
{
printf("Error sending username.\n");
close(sockfd);
return -1;
}
printf("Username sent.\n");
close(sockfd);
return 0;
}
server.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define PORT 4000
#define WORD_SIZE 256
int main(int argc, char *argv[])
{
int serverSockfd;
socklen_t clilen;
struct sockaddr_in serv_addr, cli_addr;
if ((serverSockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
printf("Error creating the socket.\n");
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
serv_addr.sin_addr.s_addr = INADDR_ANY;
if (bind(serverSockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
printf("Error binding the socket.\n");
return -1;
}
if (listen(serverSockfd, 5) < 0)
{
printf("Error on listening.\n");
return -1;
}
int newSockfd;
while (1)
{
newSockfd = accept(serverSockfd, (struct sockaddr *)&cli_addr, &clilen);
if (newSockfd < 0)
{
printf("Error on accept a new client.\n");
continue;
}
char username[WORD_SIZE];
if (recv(newSockfd, username, WORD_SIZE, 0) < 0)
{
printf("Error receiving username.\n");
close(newSockfd);
continue;
}
printf("User %s logged in.\n", username);
close(newSockfd);
}
}
I'm trying to make a client/server program in localhost but the client can not connect to the server and I do not know what I'm doing wrong.
I have tried to debug the program and all the parameters seem to be ok.The server does bind, connect, listen and accept.
With the client code a get connect: Invalid argument error. Client (I'm calling the client from the console with ./client localhost):
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
int main(int argc, char * argv[])
{
int cd;
struct hostent *hp;
struct sockaddr_in s_ain;
unsigned char byte;
hp = gethostbyname(argv[1]);
bzero((char *)&s_ain, sizeof(s_ain));
s_ain.sin_family = AF_INET;
memcpy(&(s_ain.sin_addr), hp->h_addr, hp->h_length);
s_ain.sin_port = htons(1025);
cd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if( connect(cd, (struct sockaddr*) &s_ain, sizeof(s_ain) == -1) ) {
fprintf(stderr, "connect: %s\n", strerror(errno));
return -1;
}
printf("%s\n", "IT WORKS!");
close(cd);
return 0;
}
Server:
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <stdio.h>
int main(void)
{
int sd, cd;
socklen_t size;
unsigned char byte;
struct sockaddr_in s_ain, c_ain;
sd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
bzero((char *)&s_ain, sizeof(s_ain));
s_ain.sin_family = AF_INET;s_ain.sin_family = AF_INET;
s_ain.sin_addr.s_addr = INADDR_ANY;
s_ain.sin_port = htons(1025);
if(bind(sd, (struct sockaddr *)&s_ain, sizeof(s_ain)) == -1) {
fprintf(stderr, "%s\n", "err bind");
return -1;
}
if(listen(sd, 5) == -1) {
fprintf(stderr, "%s\n", "err listen");
return -1;
}
while(1) {
size = sizeof(c_ain);
cd = accept(sd, (struct sockaddr *)&c_ain, &size);
printf("%s\n", "IT WORKS !");
}
}
Either you have a typo in your example, or
if( connect(cd, (struct sockaddr*) &s_ain, sizeof(s_ain) == -1) ) {
fprintf(stderr, "%s\n", "err connect");
return -1;
}
has wrong parenthesis. Currently you will call connect with socklen_t addrlen as 0. It should read
if( connect(cd, (struct sockaddr*) &s_ain, sizeof(s_ain)) == -1) {
fprintf(stderr, "%s\n", "err connect");
return -1;
}
Some fixes in server.c
#include <netinet/in.h> // fix
#include <sys/types.h>
#include <netdb.h>
#include <string.h>
#include <stdio.h>
int main(void)
{
int sd, cd;
unsigned char byte;
struct sockaddr_in c_ain;
sd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
bzero((char *)&c_ain, sizeof(c_ain));
c_ain.sin_family = AF_INET;
c_ain.sin_addr.s_addr = INADDR_ANY;
c_ain.sin_port = htons(1025);
bind(sd, (struct sockaddr *)&c_ain, sizeof(c_ain));
listen(sd, 5);
struct sockaddr_in t_ain;
while(1) {
int size = sizeof(t_ain); // < fix
cd = accept(sd, (struct sockaddr *)&t_ain, (socklen_t*)&size); // < fix
printf("%s\n", "IT WORKS !");
}
}
Also to test server you can use telnet:
telnet 127.0.0.1 1025
I am beginner in socket programming and reading Linux Network Programming book. I decided to implement client-server connection as shown in the book. Server program is run on Ubuntu 14.04 machine and client code is run from Mac machine. The server code is the following
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <string.h>
const char message[] = "hello, world\n";
int main()
{
int sock = 0;
int port = 0;
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1)
fprintf(stderr, "failed\n");
else
printf("connection is establisshed\n");
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_addr.s_addr = htonl(INADDR_ANY );
server.sin_port = 3500;
int status = bind(sock, (struct sockaddr*) &server, sizeof(server));
if (status == 0)
printf("connection completed\n");
else
printf("problem is encountered\n");
status = listen(sock, 5);
if (status == 0)
printf("app is ready to work\n");
else
{
printf("connection is failed\n");
return 0;
}
while (1)
{
struct sockaddr_in client = { 0 };
int sclient = 0;
int len = sizeof(client);
int childSocket = accept(sock, (struct sockaddr*) &client, &len);
if (childSocket == -1)
{
printf("cannot accept connection\n");
close(sock);
break;
}
write(childSocket, message, strlen(message));
close(childSocket);
}
return 0;
}
As for client side i wrote the following code
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
int main(int argc, char* argv[])
{
int sock = 0;
int port = 0;
struct sockaddr_in servaddr;
sock = socket(AF_INET, SOCK_STREAM, 0);
int status = 0;
char buffer[256] = "";
if (sock == -1)
{
printf("could not establish connection\n");
exit(1);
}
port = 3500;
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr(argv[1]);
servaddr.sin_port = htons(port);
status = connect(sock, (struct sockaddr*) &servaddr, sizeof(servaddr));
if (status == 0)
printf("connection is established successfully\n");
else
{
printf("could not run the app\n");
exit(1);
}
status = read(sock, buffer, sizeof(buffer));
if (status > 0)
printf("%d: %s", status, buffer);
close(sock);
return 0;
}
To get IP address of client machine I run ifconfig from terminal an get inet_addr 192.168.1.165 value. Now when I pass that address string as command line argument I get message that app is not running message. There is problem with address that I got, as I understand. So what is the problem?
Thanks in advance
Most probably the server does not listen on the port you are assuming, that is 3500.
To fix this, change this line:
server.sin_port=3500
to be
server.sin_port = htons(3500);
(To monitor which process is listing on which address:port you might like to use the netstat command line tool. In your case probably using the options -a -p -n )
Also on recent systems accept() expects a pointer to socklen_t as last parameter, so change this
int len=sizeof(client);
to be
socklen_t len = sizeof client; /* sizeof is an operator, not a function¨*/
I'm writing 2 small test programs in C (client/server) and I'm having trouble sending messages from the server to the client (but the other way around works just fine). The server says it sent 20 bytes, but on the client's end it says "failed to receive data". I would appreciate any help, thank you so much! My code is below:
Server:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netinet/in.h>
int main(int argc, char* argv[])
{
int sockfd, client_sockfd;
struct sockaddr_in server;
int reading, fileSize;
int i; //counter
int bytesSent;
char test[20] = "test message\n";
memset(&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(atoi(argv[1])); //assign port to listen to
server.sin_addr.s_addr = INADDR_ANY; //IP address
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) //create socket failed
{
perror("socket");
exit(1);
}
if(bind(sockfd, (struct sockaddr *) &server, sizeof(server)) == -1) //connect server socket to specified port
{
perror("bind call failed");
exit(1);
}
//printf("listening to port %d\n", server.sin_port);
if(listen(sockfd, 5) == -1) //queue size of 5
{
perror("listen call failed");
exit(1);
}
while(1) //infinite loop to process connections from clients
{
client_sockfd = accept(sockfd, NULL, NULL); //accept anything
if(client_sockfd == -1)
perror("accept call failed");
bytesSent = send(client_sockfd, test, 20, 0);
printf("bytes sent: %d\n", bytesSent);
}
close(client_sockfd);
close(sockfd);
return 0;
}
Client:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <fcntl.h>
#include <errno.h>
int main(int argc, char* argv[])
{
int sockfd;
struct sockaddr_in server;
struct hostent *server_ip_address;
server_ip_address = gethostbyname("eos-class.engr.oregonstate.edu");
int sent; //number of bytes sent
int received; //number of bytes received
char passedMsg[20]; //holds received message
if(server_ip_address == NULL)
{
fprintf(stderr, "could not resolve server host name\n");
exit(1);
}
memset(&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(atoi(argv[3])); //assign port to connect to
memcpy(&server.sin_addr, server_ip_address->h_addr, server_ip_address->h_length);
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) //create socket failed
{
perror("socket");
exit(1);
}
if(connect(sockfd, (struct sockaddr *) &server, sizeof(server)) == -1) //connect socket to remote address failed
{
printf("tried to connect to port %d\n", server.sin_port);
perror("connect");
exit(1);
}
if((received = recv(sockfd, passedMsg, 20, 0)) < 0);
{
printf("Failed to receive data\n");
exit(1);
}
printf("Received message: %s\n", passedMsg);
close(sockfd);
return 0;
}
In your client code, in the error checking for recv, change printf to perror. If you do, the output will be:
Failed to receive data: Success
So the recv call was successful, but the error code ran anyway. Why? Let's take a closer look at that if statement:
// what's this? ----v
if((received = recv(sockfd, passedMsg, 20, 0)) < 0);
{
printf("Failed to receive data\n");
exit(1);
}
There's a stray ; after the condition in the if statement. This means that the if statement does nothing if the condition is true, and that the following block is not the body of the if but an independent block that always runs.
Get rid of the extra ; and you get the expected results.
This code is generating "Connection Failed error", (the error generating portion is commented below in the code) even when i am supplying the correct input format eg.
./Client ip text portno
./Client 127.0.0.1 "tushar" 7100
//AUTHOR: TUSHAR MAROO
//Client.c
//header files used
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <netinet/in.h>
//constants
#define RCVBUFFERSIZE 32
//functions used
void DieWithError(char *errorMessage);
//main program
int main(int argc, char *argv[]){
int sock;
struct sockaddr_in serverAddr;
unsigned short serverPort;
char *serverIp;
char *message;
unsigned int messageLength;
char buffer[RCVBUFFERSIZE];
//condition check deplyed for nuber of arguements not for data in arguements
if((argc<3) || (argc>4)){
fprintf(stderr,"Format: %s <Server's IP> <Your Message> <Port Number>\n",argv[0]);
exit(1);
}
serverIp = argv[1];
message = argv[2];
if(argc == 4){
serverPort = atoi(argv[3]);
} else {
serverPort = 7;
}
//create a socket and check success and handle error
if((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0 )
fprintf(stderr, "Socket Creation Fail");
//server details
//bzero((struct sockaddr_in *)(&serverAddr),sizeof(serverAddr));
memset(&serverAddr, 0, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = inet_addr(serverIp);
serverAddr.sin_port = htons(serverPort);
printf("tusharmaroo");
//not working why??
//if (connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0)
//DieWithError("Connection Error..");
//fprintf(stderr,"Connection error");
//this snippet also not working
if (connect(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0)
DieWithError("connect() failed");
printf("connected....");
messageLength = strlen(message);
if(send(sock, message, messageLength, 0) > 0)
printf("message sent....");
close(sock);
exit(0);
}
//AUTHOR TUSHAR MAROO
//SERVER CODE
//header files
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <netinet/in.h>
//constants declared
#define ALLOWEDCONNECTIONS 5
//external functions
void DieWithError(char *error);
void ClientHandle(int sock);
//main code
int main(int argc, char argv[]){
int serverSock;
int clientSock;
struct sockaddr_in serverAddr;
struct sockaddr_in clientAddr;
unsigned int serverPort;
unsigned int clientLength;
if(argc != 2){
fprintf(stderr,"Format: %d <Port No.>", argv[0]);
//DieWithError("Pass Correct Number of Arguements...");
exit(1);
}
if((serverSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0){
DieWithError("Socket not Created");
exit(1);
}
serverPort = htons((argv[1]));
//assign address to the server
memset(&serverAddr, 0, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
serverAddr.sin_port = htons(serverPort);
//socket has been created now bind it to some ip and port
if((bind(serverSock,(struct sockaddr *)&serverAddr,sizeof(serverAddr))) < 0){
DieWithError("Binding Failed");
}
if(listen(serverSock,5) < 0){
DieWithError("Listen Failed");
}
for(;;){
clientLength = sizeof(clientAddr);
if((clientSock = accept(serverSock, (struct sockaddr *) &clientAddr, &clientLength)) < 0){
DieWithError("Accept() failed");
exit(1);
}
printf("Handling Client %s ",inet_ntoa(clientAddr.sin_addr));
}
return 0;
}
This is wrong in the server code
serverPort = htons((argv[1]));
This should be
serverPort = htons(atoi(argv[1]));
Are you sure there are no firewall rules causing troubles for you? Ensure that.
If the connect fails you should be able to print out the error using perror or strerror:
perror("Could not connect:");
works for me
client and server are ubuntu 12.04
for server, run in a shell
nc -l 9999
This is on a host with the address "192.168.56.13"
for client, compile code above with "DieWithError" fixed up
void DieWithError(char *errorMessage) { printf("%s",errorMessage); exit(1); }
cc -o foo foo.c
./foo 192.168.56.13 "hello" 9999</strike>
replace the DieWithError() with perror() Then I would guess that it will print out "connection refused" as you seem to have a networking problem with getting the server running on the correct address.
However, if the address in your client is correct the nc program WILL print "hello"
you just altered your program the previous version worked for me. The current version, I don't know if it does.
Like everyone else is saying, use perror() to get proper diagnostics