Error connection to remote server in socket programming using c - c

It is a sample code where i have tried to pass a request to server and get me the desired data.
But my connect to remote server code is not working as i thought.
if (connect(s , (struct sockaddr *)&server , sizeof(server)) < 0)
{
puts("connect error");
return 1;
}
puts("Connected");
I don't know why value of the condition is getting below zero.Why connection is not getting done?
Full code:
/*
Create a TCP socket
*/
#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;
char *message , server_reply[2000];
int recv_size;
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.235.20");
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");
//Send some data
message = "GET / HTTP/1.1\r\n\r\n";
if( send(s , message , strlen(message) , 0) < 0)
{
puts("Send failed");
return 1;
}
puts("Data Send\n");
//Receive a reply from the server
if((recv_size = recv(s , server_reply , 2000 , 0)) == SOCKET_ERROR)
{
puts("recv failed");
}
puts("Reply received\n");
//Add a NULL terminating character to make it a proper string before printing
server_reply[recv_size] = '\0';
puts(server_reply);
closesocket(s);
WSACleanup();
return 0;
}

You need to initalize the whole sockaddr_in to zero before assigning to it.
memset( &server, 0, sizeof(server) );
server.sin_addr.s_addr = inet_addr("74.125.235.20");
server.sin_family = AF_INET;
server.sin_port = htons( 80 );
I copied your code and tried it out and it seemed to work, maybe you have a firewall that is interfering.
BTW I changed your inet_addr call to
InetPtonA( AF_INET, "74.125.235.20", &server.sin_addr.s_addr );

Related

C socket successfully accept() but fails on recv()

I am trying to implement a server which accepts 2 connections one after another each of them sending data. My client-side can connect and fwrite successfully whereas my server-side connects successfully but fails to recv() anything. I have tried many things on the net but I could not resolve this. Why would recv() fail in this code after succesfully accepting and connecting on the socket?
Code of Server part —— Successful on accept() but fail on recv()
char** get_host_ip(){
char** arr = malloc(3* sizeof(char*));
int x;
for(x=0; x<3;x++){
arr[x] = malloc(256 *sizeof(char));
}
int socket_desc , client_sock , c , *new_sock;
struct sockaddr_in server , client;
fd_set fdset;
struct timeval tv;
//Create socket
socket_desc = socket(AF_INET , SOCK_STREAM , 0);
//fcntl(socket_desc, F_SETFL, O_NONBLOCK);
if (socket_desc == -1)
{
printf("Could not create socket");
}
puts("Socket created");
//Prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons( 8888 );
int reuse = 1;
if (setsockopt(socket_desc, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(int)) < 0){
perror("setsockopt(SO_REUSEADDR) failed");
}
if(setsockopt(socket_desc, SOL_SOCKET, SO_REUSEPORT, &reuse, sizeof(int)) < 0){
perror("setsockopt(SO_REUSEPORT) failed");
}
//Bind
if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0)
{
//print the error message
perror("bind failed. Error");
char* err = "Error on binding\r\n";
printf("%s\r\n",err);
}
puts("bind done");
//Listen
listen(socket_desc , 20);
//Accept and incoming connection
puts("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);
int k;
for(k=0; k<2; k++){
client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c);
if(client_sock < 0){
puts("Accept failed\r\n");
exit(0);
}
else{
puts("Accept succeeded");
}
if(k == 0) {
char* host_ip = inet_ntoa(client.sin_addr);
printf("IP address is: %s\n", inet_ntoa(client.sin_addr));
printf("port is: %d\n", (int) ntohs(client.sin_port));
strcpy(arr[k],host_ip);
int read_size = 0;
char readBuf[256];
if((read_size = recv(client_sock , readBuf , 256 , 0)) > 0){
printf("readBuf: %s\r\n",readBuf);
strcpy(arr[k+1],readBuf);
memset(readBuf,0,256);
}
else{
printf("Receive has failed.. read_size: %d\r\n",read_size);
}
}
else {
int read_size;
char readBuf[256];
if((read_size = recv(client_sock , readBuf , 256 , 0)) > 0){
printf("readBuf: %s\r\n",readBuf);
strcpy(arr[k+2],readBuf);
memset(readBuf,0,256);
}
else{
printf("Receive has failed.. read_size: %d\r\n",read_size);
}
}
}
close(client_sock);
close(socket_desc);
return arr;
}
Client part —— connect() and fwrite() successful
void give_envi(char* env_var) {
printf("The environment variable sent: %s\r\n",env_var);
int receive_no = 1;
int sock;
struct sockaddr_in server;
//Create socket
sock = socket(AF_INET , SOCK_STREAM , 0);
if (sock == -1)
{
printf("Could not create socket");
}
//puts("Socket created");
//char host_ip[20];
//strcpy(host_ip,getenv("HOST_IP"));
server.sin_addr.s_addr = inet_addr("127.0.0.1"); //PROVIDE THE IP OF THE TARGET TO SEND YOUR DATA.
server.sin_family = AF_INET;
server.sin_port = htons( 8888 );
int reuse = 1;
if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(int)) < 0){
perror("setsockopt(SO_REUSEADDR) failed");
}
if(setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &reuse, sizeof(int)) < 0){
perror("setsockopt(SO_REUSEPORT) failed");
}
//Connect to remote server
if ( connect(sock , (struct sockaddr *)&server , sizeof(server)) > -1) {
puts("Connection established!\r\n");
}
else{
puts("Connection failed\r\n");
}
FILE * file = fdopen(sock, "w");
if(fwrite (env_var ,sizeof(char), strlen(env_var), file) == strlen(env_var)){
printf("fwrite() SUCCESS\r\n");
}
else{
printf("FAILED on fwrite()\r\n");
}
close(sock);
}

Sending data via a WebSocket from a c program to a node-red server

I wanted to send data from my C code using libc websocket library to my node-red Server.
the code in c below :
#include<stdio.h>
#include<string.h> //strlen
#include<sys/socket.h>
#include<arpa/inet.h> //inet_addr
int main(int argc , char *argv[])
{
int socket_desc;
struct sockaddr_in server;
char *message , server_reply[2000];
//Create socket
socket_desc = socket(AF_INET , SOCK_STREAM , 0);
if (socket_desc == -1)
{
printf("Could not create socket");
}
server.sin_addr.s_addr = inet_addr(myIpaddr);
server.sin_family = AF_INET;
server.sin_port = htons( 1880 );
//Connect to remote server
if (connect(socket_desc , (struct sockaddr *)&server , sizeof(server)) < 0)
{
puts("connect error");
return 1;
}
puts("Connected\n");
//Send some data
message = "SensorDataTest";
if( send(socket_desc , message , strlen(message) , 0) < 0)
{
puts("Send failed");
return 1;
}
puts("Data Send\n");
//Receive a reply from the server
if( recv(socket_desc, server_reply , 2000 , 0) < 0)
{
puts("recv failed");
}
puts("Reply received\n");
puts(server_reply);
return 0;
}
The probleme is in Node-red I have to specify the path of the socket for example when I send data from a Javascript code I use this address :
ws://myipaddr:1880/pathofsocket.
Now what I want to know is how I can add the "pathofsocket" to my c code.
Thanks.

Winsock client and server wont connect

I have written a client and server using winsock2. The server seems to run fine but when I run the client it returns the 10038 error code for "Socket operation on nonsocket" immediately. Not sure why its doing that at is will create the socket with returning an error.
Here is the code for the client, It fails on the connect function call:
#include <stdio.h>
#include <winsock2.h>
#include <time.h>
#pragma comment(lib,"ws2_32.lib") //Winsock Library
int main(int *argc, char **argv){
struct sockaddr_in server, client;
char server_reply[2000];
WSADATA wsa;
int result = WSAStartup(MAKEWORD(2,2),&wsa);
SOCKET sock, newSock;
if ((sock = socket(AF_INET, SOCK_STREAM, 0) == INVALID_SOCKET)){
printf("Failed to create socketwith error code : %d" , WSAGetLastError());
}
else{
printf("Socket created\n");
}
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_family = AF_INET;
server.sin_port = htons(8080);
if((newSock = connect(sock , (struct sockaddr *)&server , sizeof(server)) == INVALID_SOCKET )){
printf("connect failed with error code : %d" , WSAGetLastError());
}
else{
printf("connected");
}
closesocket(socket);
WSACleanup();
return 0;
}
The code for the server which I believe works:
#include<io.h>
#include<stdio.h>
#include<winsock2.h>
#pragma comment(lib,"ws2_32.lib") //Winsock Library
int main(int argc , char *argv[])
{
WSADATA wsa;
SOCKET s , new_socket;
struct sockaddr_in server , client;
int c;
char message[54];
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");
//Prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons( 8080 );
//Bind
if( bind(s ,(struct sockaddr *)&server , sizeof(server)) == SOCKET_ERROR)
{
printf("Bind failed with error code : %d" , WSAGetLastError());
return 1;
}
puts("Bind done");
//Listen to incoming connections
listen(s , 3);
//Accept and incoming connection
puts("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);
while( (new_socket = accept(s , (struct sockaddr *)&client, &c)) != INVALID_SOCKET )
{
recv(s, message, 2000, 0);
printf(message);
}
if (new_socket == INVALID_SOCKET)
{
printf("accept failed with error code : %d" , WSAGetLastError());
return 1;
}
closesocket(s);
WSACleanup();
return 0;
}
You are setting the parentheses wrong:
if ((sock = socket(AF_INET, SOCK_STREAM, 0) == INVALID_SOCKET))
assigns 0 to "sock", you want the following:
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
to have the comparison after the assignment, instead of assigning the result of the comparison. This is a matter of operator precedence, == "winning" over =.

Unable to print message from server side to client side before sending any message from client

I have two programs for server and client. My server can connect to multiple client. But the problem right now I am facing is that, I want to display some message from the server side to client side but I am unable to do that. Both the server and client program are provided below. I think the syntax that is preventing me to print the message on the client side is scanfwhich is used the code of client (second line of the while loop). I am not getting any solution for that about how to display the two messages from the server side when the client will get connected.
Problem 1:
Server side messages that I want to display on the client side when client gets connected : (can be found in the new_connection_handler function)
message = "This is connection handler\n";
message = "Type something \n";
Problem 2:
Why I need to use the sleep (2) on the client side? If I do not use the sleep (2), then I cannot receive the data sent by the client on the client side. The data shows when I send something second time from the client side.
Problem 3:
Is it possible to write both the client and server code together and compile and run it using command line arguments?
Server Code:
#include<stdio.h>
#include<string.h> //strlen
#include<stdlib.h> //strlen
#include<sys/socket.h>
#include<arpa/inet.h> //inet_addr
#include<unistd.h> //write
#include<pthread.h> //for thread
#define MAX_CLIENTS 5
//the thread function
void *new_connection_handler(void *);
int main(int argc , char *argv[])
{
int socket_desc , client_sock , c , *new_sock;
struct sockaddr_in server , client;
//Create socket
socket_desc = socket(AF_INET , SOCK_STREAM , 0);
if (socket_desc == -1)
{
printf("Could not create socket");
}
//Prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons( 8888 );
bzero (&server.sin_zero, 8);
//Bind
if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0)
{
//print the error message
perror("bind failed. Error");
return 1;
}
//Listen
listen(socket_desc , MAX_CLIENTS);
//Accept and incoming connection
printf("Waiting for incoming connections\n");
c = sizeof(struct sockaddr_in);
while( (client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c)) )
{
printf("Connection accepted");
pthread_t thread_id;
if( pthread_create( &thread_id , NULL , new_connection_handler , (void*) &client_sock) < 0)
{
perror("could not create thread");
return 1;
}
printf("Handler assigned\n");
}
if (client_sock < 0)
{
perror("accept failed");
return 1;
}
return 0;
}
void *new_connection_handler(void *socket_desc)
{
//Get the socket descriptor
int sock = *(int*)socket_desc;
int read_size;
char *message , client_message[2000];
//Send some messages to the client
message = "This is connection handler\n";
write(sock , message , strlen(message));
message = "Type something \n";
write(sock , message , strlen(message));
//Receive a message from client
while( (read_size = recv(sock , client_message , 2000 , 0)) > 0 )
{
//Send the message back to client
write(sock , client_message , strlen(client_message));
}
if(read_size == 0)
{
printf("Client disconnected\n");
fflush(stdout);
}
else if(read_size == -1)
{
perror("recv failed");
}
//Free the socket pointer
free(socket_desc);
return 0;
}
Client Code:
#include<stdio.h> //printf
#include<string.h> //strlen
#include<sys/socket.h> //socket
#include<arpa/inet.h> //inet_addr
int main(int argc , char *argv[])
{
int sock;
struct sockaddr_in server;
char message[1000] , server_reply[2000];
int len;
//Create socket
sock = socket(AF_INET , SOCK_STREAM , 0);
if (sock == -1)
{
printf("Could not create socket");
}
puts("Socket created");
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_family = AF_INET;
server.sin_port = htons( 8888 );
//Connect to remote server
if (connect(sock , (struct sockaddr *)&server , sizeof(server)) < 0)
{
perror("connect failed. Error");
return 1;
}
puts("Connected\n");
//keep communicating with server
while(1)
{
printf("Enter message : ");
scanf("%s" , message);
//Send some data
if( send(sock , message , strlen(message) , 0) < 0)
{
puts("Send failed");
return 1;
}
sleep (2);
//Receive a reply from the server
if((len = recv(sock , server_reply , 2000 , 0)) < 0)
{
puts("recv failed");
break;
}
puts("Server reply :");
server_reply [len]='\0';
printf("%s\n", server_reply);
}
close(sock);
return 0;
}
Your frames are out of sync You open your client handling thread with two sends from the server. Without your "sleep", you pick up one, but not the other. your buffer sizes are also not being used correctly, as they're inconsistently being treated as terminated strings when in fact their send length is based on strlen (which is ok, so long as it is consistent).
I think this is what you're trying to do, with a few modifications:
Client Code
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdint.h>
int main(int argc , char *argv[])
{
int sock;
struct sockaddr_in server;
char message[1000] , server_reply[2000];
int len;
//Create socket
sock = socket(AF_INET , SOCK_STREAM , 0);
if (sock == -1)
{
printf("Could not create socket");
}
puts("Socket created");
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_family = AF_INET;
server.sin_port = htons( 8888 );
//Connect to remote server
if (connect(sock , (struct sockaddr *)&server , sizeof(server)) < 0)
{
perror("connect failed. Error");
return 1;
}
puts("Connected\n");
//keep communicating with server
while((len = recv(sock, server_reply, sizeof(server_reply), 0)) > 0)
{
printf("Server reply: %.*s", len, server_reply);
printf("Enter message : ");
if (fgets(message, sizeof(message), stdin) == NULL)
break;
//Send some data
if( send(sock , message , strlen(message) , 0) < 0)
{
puts("Send failed");
return 1;
}
}
close(sock);
return 0;
}
Server Code
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<pthread.h>
#include<stdint.h>
#define MAX_CLIENTS 5
//the thread function
void *new_connection_handler(void *);
int main(int argc , char *argv[])
{
int socket_desc , client_sock;
struct sockaddr_in server , client;
socklen_t c = sizeof(client);
//Create socket
socket_desc = socket(AF_INET , SOCK_STREAM , 0);
if (socket_desc == -1)
{
printf("Could not create socket");
}
//Prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons( 8888 );
bzero (&server.sin_zero, 8);
//Bind
if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0)
{
//print the error message
perror("bind failed. Error");
return 1;
}
//Listen
listen(socket_desc , MAX_CLIENTS);
//Accept and incoming connection
printf("Waiting for incoming connections\n");
c = sizeof(client);
while( (client_sock = accept(socket_desc, (struct sockaddr *)&client, &c)) )
{
printf("Connection accepted");
pthread_t thread_id;
if( pthread_create( &thread_id , NULL , new_connection_handler , (void*) (intptr_t)client_sock) < 0)
{
perror("could not create thread");
return 1;
}
printf("Handler assigned\n");
}
if (client_sock < 0)
{
perror("accept failed");
return 1;
}
return 0;
}
void *new_connection_handler(void *socket_desc)
{
//Get the socket descriptor
int sock = (intptr_t)socket_desc;
int read_size = 0;
char client_message[2000];
static const char rdy[] = "READY\n";
write(sock, rdy, sizeof(rdy)-1);
//Receive a message from client
while( (read_size = recv(sock , client_message , sizeof(client_message) , 0)) > 0 )
write(sock , client_message , read_size);
if(read_size == 0)
{
printf("Client disconnected\n");
fflush(stdout);
}
else if(read_size == -1)
{
perror("recv failed");
}
return 0;
}
This still needs better join-logic on the client threads, but if you paste and compile each with appropriate flags I think it does what you're trying to achieve.
Best of luck.

Unable to receive correct data in socket client side

Below is my socket client program. I am trying to send some data from client and trying to receive it in the client side. When I run the program, there is no compilation error. But I am unable to receive the sent message correctly in the client side. I think I am doing some error in
server_reply [len]='\0';
printf("%s\n", server_reply);
My original code is written below: (you can find my server program here in this link Multiple client not getting connected and cannot communicate at the same time)
#include<stdio.h> //printf
#include<string.h> //strlen
#include<sys/socket.h> //socket
#include<arpa/inet.h> //inet_addr
int main(int argc , char *argv[])
{
int sock;
struct sockaddr_in server;
char message[1000] , server_reply[2000];
int len;
//Create socket
sock = socket(AF_INET , SOCK_STREAM , 0);
if (sock == -1)
{
printf("Could not create socket");
}
puts("Socket created");
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_family = AF_INET;
server.sin_port = htons( 8888 );
//Connect to remote server
if (connect(sock , (struct sockaddr *)&server , sizeof(server)) < 0)
{
perror("connect failed. Error");
return 1;
}
puts("Connected\n");
//keep communicating with server
while(1)
{
printf("Enter message : ");
scanf("%s" , message);
//Send some data
if( send(sock , message , strlen(message) , 0) < 0)
{
puts("Send failed");
return 1;
}
//Receive a reply from the server
if(len = (recv(sock , server_reply , 2000 , 0)) < 0)
{
puts("recv failed");
break;
}
puts("Server reply :");
server_reply [len]='\0';
printf("%s\n", server_reply);
}
close(sock);
return 0;
}
This line is wrong.
if (len = (recv(sock , server_reply , 2000 , 0)) < 0)
{
puts("recv failed");
break;
}
Should be:
if ((len = recv(sock , server_reply , 2000 , 0)) < 0)
{
puts("recv failed");
break;
}

Resources