Socket Programming: Client printing garbage string - c

I am new to Network Programming and the first program we were supposed to do in our lab was a program where two systems, client and the server send messages to each other. My program has no compiler errors, but whenever a message is sent over the network, it is not being displayed properly on the other end. Instead an unreadable box is being displayed (I think a garbage string is being printed but don't know why).
View the screenshot here
The codes:
client.c
int main()
{
char server_message[256]="You have reached the server!!\n";
//create a socket
int nw_socket;
nw_socket=socket(AF_INET,SOCK_STREAM,0);
//specify address for socket
struct sockaddr_in server_address;
server_address.sin_family = AF_INET;
server_address.sin_port = htons(9999);
server_address.sin_addr.s_addr = INADDR_ANY;
//establish a connection
int connection_status = connect(nw_socket, (struct sockaddr *) & server_address, sizeof(server_address));
//check for errors
if(connection_status==-1)
{
perror("There was a problem initiating the connection.\n");
}
else
{
printf("The connection was successful.\n");
}
int send_val = send(nw_socket,server_message,sizeof(server_message),0);
if(send_val==-1)
perror("\nError while sending: ");
//receive data
char data[256];
int recv_val=recv(nw_socket,data,sizeof(data),0);
if(recv_val==-1)
perror("\nError while receiving: ");
printf("The server's response was: %s\n",data );
//close the socket
close(nw_socket);
return 0;
}
server.c
int main()
{
char server_message[256]="You have reached the server!!\n";
//create a new socket
int server_socket=socket(AF_INET,SOCK_STREAM,0);
struct sockaddr_in server_connection;
server_connection.sin_family=AF_INET;
server_connection.sin_port=htons(9999);
server_connection.sin_addr.s_addr=INADDR_ANY;
int bind_val=bind(server_socket, (struct sockaddr *) & server_connection, sizeof(server_connection));
if(bind_val==-1)
perror("\nError while binding: ");
listen(server_socket,6);
int client_socket=accept(server_socket, NULL, NULL);
if(client_socket==-1)
perror("\nError while accepting: ");
int send_val= send(server_socket,server_message,sizeof(server_message),0);
if(send_val==-1)
perror("\nError while sending: ");
char data[256];
recv(server_socket,data,sizeof(data),0);
close(server_socket);
return 0;
}
How do I fix this? Thanks in advance.

You are using the listening socket when sending a message in the server:
int send_val= send(server_socket,server_message,sizeof(server_message),0);
You should be using the socket connected to the client:
int send_val = send(client_socket,server_message,sizeof(server_message),0);

Related

Use of connect after recvfrom with socket

Hi i want to wait the first message of a client as a server with a UDP Protocol so i send a message when I create the client socket and I use a recvfrom to get the message and the adress of the client.It works pretty good I can read the message in my buffer but after this operation I try to connect the server to the client address but this operation return a value of -1 for the connect process and I don't understand the reason.Here is my function wait for client the error is at the end when I try to connect to clientaddr.
int wait_for_client(int sfd){
struct sockaddr_in clientaddr;
int len;
char buf[32];
len = sizeof(clientaddr);
int rec_stat = recvfrom(sfd, buf, 32, 0, (struct sockaddr*)&clientaddr, (socklen_t *)&len);
if(rec_stat<0){
printf("echec de receive");
fflush(stdout);
return -1;
}
printf("%s\n",buf);
fflush(stdout);
int connect_status = connect(sfd,(struct sockaddr *)&clientaddr,sizeof(clientaddr));
if(connect_status == -1){
printf("failed to connect to client\n");
fflush(stdout);
return -1;
}
printf("%s\n",buf);
return sfd;
}
The problem was because my clientaddr is declared as sockaddr_in but my client was created as sockaddr_in6. So the mistake was the struct of my clientaddr

Why is my C Socket client failing to receive data and it is failing with an error code of 104. Some code is also not being execute

I have a very big problem that I have encountered with C. I wrote a C client program with a function that is supposed to send and receive data from a server also written in C. But it throws an error. 104. Below is the code for the function.
int send_and_receive_data(struct PatientData c, int rcv)
{
//recv is supposed to determine whether data will be received from the server. it's an integer that can either be 1 or 0
if (rcv)
{
/*create socket*/
int network_socket;
network_socket = socket(AF_INET,SOCK_STREAM,0);
//specify an address for the socket
struct sockaddr_in server_address;
server_address.sin_family = AF_INET;
server_address.sin_port = htons(9002);
server_address.sin_addr.s_addr = INADDR_ANY;
int connection_status = connect(network_socket,(struct sockaddr *) &server_address, sizeof(server_address));
// check for error with the connection
if(connection_status == -1){
printf("There was an error making a connection to the remote socket\n\n");
}
//send data to the server
if(send(network_socket,&c,sizeof(c),0) < 0){
puts("Send Failed\n");
}
else
{
//puts("Data sent\n");
}
if(recv(network_socket,&s_results,sizeof(s_results),0) < 0)
{
printf("Receive Failed %d\n",errno);
printf("Sara Nakamya 2019-01-01 F Mary\n");
}
else
{
// output the received data
puts("Receive successful");
printf("%s %s %s %s\n",s_results.patient_name,s_results.patient_date,s_results.patient_category,s_results.patient_gender);
}
// and then close the socket
close(network_socket);
}
else
{
/*create socket*/
int network_socket;
network_socket = socket(AF_INET,SOCK_STREAM,0);
//specify an address for the socket
struct sockaddr_in server_address;
server_address.sin_family = AF_INET;
server_address.sin_port = htons(9002);
server_address.sin_addr.s_addr = INADDR_ANY;
int connection_status = connect(network_socket,(struct sockaddr *) &server_address, sizeof(server_address));
// check for error with the connection
if(connection_status == -1){
printf("There was an error making a connection to the remote socket\n\n");
}
//send data to the server
if(send(network_socket,&c,sizeof(c),0) < 0){
puts("Send Failed\n");
}
else
{
puts("Data sent\n");
}
// and then close the socket
close(network_socket);
}
return 0;
}
The function sends data to the server and also receives data on the same connection. Now my problem is that the recv() function call always fails with an error code of 104 even when the server has sent data back to the client socket.
Below is the code for the server
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
/*
Input Data using commands
Send data to the server
The server writes the data to a text file
Database connection in C
*/
struct patient_data
{
char patient_name[256];
char patient_date[256];
char patient_category[256];
char patient_gender[10];
} s_results;
int main()
{
// create the server socket
int server_socket;
server_socket = socket(AF_INET,SOCK_STREAM,0);
// define the server address
struct sockaddr_in server_address;
server_address.sin_family = AF_INET;
server_address.sin_port = htons(9002);
server_address.sin_addr.s_addr = INADDR_ANY;
// bind the socket to our specified IP and port
bind(server_socket, (struct sockaddr*) &server_address,sizeof(server_address));
listen(server_socket,100);
int client_socket;
client_socket = accept(server_socket,NULL,NULL);
struct data
{
int type;
char name[100];
char date_of_identificaton[20];
char category[10];
char gender[5];
} response;
// receive data from server
recv(client_socket,&response,sizeof(response),0);
if(response.type == 1)
{
puts("Check_status");
char name[] = "Okello Ivan ELijah";
char date[] = "2019-01-01";
char category[] = "Ass";
char gender[] = "M";
strcpy(s_results.patient_name,name);
strcpy(s_results.patient_date,date);
strcpy(s_results.patient_category,category);
strcpy(s_results.patient_gender,gender);
send(server_socket,&s_results,sizeof(s_results),0);
puts("Data sent\n");
printf("%s\n%d\n%s\n",response.name,response.type,response.gender);
}
else
{
puts("Data not sent");
}
// close the socket
close(server_socket);
return 0;
}
The server also does not execute the if statement fully. It just executes the first statement of the if else statement and doesn't execute the others. What could be the problem??
Please help me with this anybody
... even when the server has sent data back to the client socket.
Actually, your server does not send data to the client. You probably intended it with this line in the server:
send(server_socket,&s_results,sizeof(s_results),0);
Only, this is using server_socket which is the listener socket. Instead it should have used client_socket, which is the connected socket. Note that if you would have checked the send call for errors you would have realized that the send has failed too. Thus, better check for errors on all places.

message from client to server in C

I have such a task, I need to write the “client” code so that the message from the “client” is sent to the server (which was created by my teacher, ip “127.0.0.1”). After the message arrives at the server (for example, “Nursultan Nazarbayev”, the server will reply “ok” and the client should send “quit”)
I'm just learning C. How to make a break with the server? I wanted to send "quit", but this did not work, there was a constant error, how can I do this?
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char **argv)
{
char message[2048];//=(char*)malloc(sizeof(char));// transmission message
char buf[sizeof(message)];
int port,ch;
//----------------------------------------------------------------------------
if(argc!=3){
printf("Wrong number of arguments!\nThere must be 2 arguments (Port, server ip-address)!\n");
exit(0);
}
int sock; // socket descriptor
struct sockaddr_in addr; // structure with address
struct hostent* hostinfo;
port = atoi(argv[1]);
hostinfo = argv[2];
sock = socket(AF_INET, SOCK_STREAM, 0); // create TCP socket
if(sock < 0)
{
perror("socket");
exit(1);
}
// Specify server parameters
addr.sin_family = AF_INET; // Internet domains
addr.sin_port = htons(port); // or any other port ...
addr.sin_addr.s_addr=inet_addr("hostinfo");
// addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
//addr.sin_addr.s_addr = inet_addr(host_ip);
if(connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) // establishing a connection to the server
{
perror("Connection");
exit(2);
}
while(1){//WHILE <---
//----------------------------------------------------------------------------
printf("Enter a message to the server (To exit: quit): ");
if (!strcmp(gets(message), "quit")){close(sock);return 0;}
//----------------------------------------------------------------------------
printf("sending a message to the server...\n");
send(sock, message, sizeof(message), 0); // sending a message to the server
int bytes_read = 0;
printf("Message Waiting\n");
bytes_read = recv(sock, buf, sizeof(message), 0);
printf("received %d bytes\tMessage: %s\n", bytes_read, buf); // receiving a message from the server
}//END_WHILE
return 0;
}
This probably is wrong:
addr.sin_addr.s_addr=inet_addr("hostinfo");
You are passing the literal string, "hostinfo" to the inet_addr() function. Meanwhile, you have a variable named hostinfo, to which you assign a string value, but you never use it anywhere in the program.
Maybe you meant to do this instead:
addr.sin_addr.s_addr=inet_addr(hostinfo);
P.S., I like long, descriptive names. If that was my program, the name of the variable would be something like, server_address_as_string.

Two clients write on server and another client read from it with socket in C

I'm new in socket programming.
My program creates two clients that write to a server, this server reads data using threads and then prints them. I would like to send all this data to another client when it makes a request. Have I to create another socket or is it possible to use the same used before?
Here is my code.
Thanks.
Server.c
#include<stdio.h>
#include<stdlib.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<string.h>
#include <arpa/inet.h>
#include <fcntl.h> // for open
#include <unistd.h> // for close
#include<pthread.h>
struct message { //dichiarazione struct
time_t timestamp;
char g; //process identifier
int x;
};
struct message client_message[10000];
int q=0;
static void * socketThread(void *arg)
{
int newSocket = *((int *)arg);
while(read(newSocket , &client_message[q] , sizeof(client_message))!=0) {
printf("message %d %d %ld\n",client_message[q].x,client_message[q].g,client_message[q].timestamp);
fflush(stdout);
sleep(1);
q++;
}
pthread_exit(NULL);
}
int main(){
int serverSocket, newSocket;
struct sockaddr_in serverAddr;
struct sockaddr_storage serverStorage;
socklen_t addr_size;
//Create the socket.
serverSocket = socket(AF_UNIX, SOCK_STREAM, 0);
// Configure settings of the server address struct
// Address family = Internet
serverAddr.sin_family = AF_UNIX;
//Set port number, using htons function to use proper byte order
serverAddr.sin_port = htons(55555);
//Set IP address to localhost
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
//INADDR_ANY;
//Set all bits of the padding field to 0
memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero);
//Bind the address struct to the socket
bind(serverSocket, (struct sockaddr *) &serverAddr, sizeof(serverAddr));
//Listen on the socket, with 40 max connection requests queued
if(listen(serverSocket,50)==0)
printf("Listening\n");
else
printf("Error\n");
pthread_t tid[2];
int i = 0;
while(i<2)
{
//Accept call creates a new socket for the incoming connection
addr_size = sizeof serverStorage;
newSocket = accept(serverSocket, (struct sockaddr *) &serverStorage, &addr_size);
//for each client request creates a thread and assign the client request to it to process
//so the main thread can entertain next request
if( pthread_create(&tid[i], NULL, socketThread, &newSocket) != 0 )
printf("Failed to create thread\n");
i++;
}
pthread_join(tid[1], NULL);
pthread_join(tid[0], NULL);
for(i=0;i<50;i++){
printf("%d aaa %d\n",client_message[i].x,client_message[i].g);
}
close(newSocket);
return 0;
}

how can i display client address using c socket program?

My project is : Client receives the raw packet from the Ethernet saves it in a file called 'sniff_data.bin' and sends it to the server. Server receives the contents processes the packet( distinguishes between tcp,icmp,udp etc) and saves in a text file called 'info_agent_ report. txt' file. i think there is some mistake in my code. can anybody please guide me , help me out.
int main()
{
int sockfd, new_sockfd,log,n,x1,x2;
int server_len, client_len,len;
int cont,fh,cont2,x;
int result1;
struct sockaddr_in serveraddress;
struct sockaddr_in address;
struct sockaddr_in client_address;
FILE *ia_address;
char *fname = "/home/shishira/Desktop/packet_capture/info_agent_report.txt";
int buffsize=1024;
char buffer1[1024];
char buffer[1024];
char clntName[INET_ADDRSTRLEN];
if((sockfd = socket(AF_INET,SOCK_STREAM,0))>0)
printf("\n ---------------------------Task Agent---------------------------\n");
printf("\n Socket was created\n");
/* Name the socket. */
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr("127.0.0.1");
address.sin_port = htons(9734);
server_len = sizeof(address);
bind(sockfd, (struct sockaddr *)&address, server_len);
/* Create a connection queue and wait INFO_AGENT_REPORTS */
listen(sockfd, 5);
while(1)
{
char ch;
printf("\n\n Task agent waiting...\n");
/* Accept a connection to collect report from INFO_AGENT */
client_len = sizeof(client_address);
new_sockfd = accept(sockfd,(struct sockaddr *)&client_address, &client_len);
if (new_sockfd==-1) { perror("Connection Not Accepted!!"); return(1);}
else
{
// x=fork();
// if (x==0) // child process starts
// {
printf("\n Information agent is connected\n");
//for displaying the client address
if(inet_ntop(AF_INET,&client_address.sin_addr.s_addr,clntName,sizeof(clntName))!=NULL)
{
ia_address = fopen("info_agent_report.txt","a+");
fprintf(ia_address,"\nFrom InformationAgent:%s\n",clntName);
fclose(ia_address);
}
printf("\n Task agent processed the contents and saved it in 'info_agent_report'
file\n\n");
log=open("info_agent_report.txt",O_CREAT|O_RDWR|O_APPEND,0777);
if(log==-1)
{
perror("cannot open info_agent_report file\n");
return(1);
}
do
{
x1=read(new_sockfd, buffer1, 1024);
x2=write(log,buffer1,x1);
}
while (x1>0);
data_process();//for processing the packet
close(log);
// } child process ends
close(new_sockfd);
}
}
I have written the code for displaying the client address in info_agent_report.txt. but is not getting dispalyed :(
To display client name: ( put this after accept )
char clntName[INET_ADDRSTRLEN]; // String to contain client address
if (inet_ntop(AF_INET, &clntAddr.sin_addr.s_addr, clntName,sizeof(clntName)) != NULL){
printf("Handling client %s/%d\n", clntName, ntohs(clntAddr.sin_port));
}
Or this:
char clntName[INET6_ADDRSTRLEN];
char portName[6];
if(getnameinfo(&client_address,sizeof client_address,clntName,sizeof(clntName),NULL,0,NI_NUMERICHOST|NI_NUMERICSERV|NI_NUMERICSCOPE)==0){
printf("Client = %s/%s\n",clntName,portName);
} else {
printf("Unable to get address\n");
}

Resources