Linux C socket - keep server alive - c

I'm using C to implement a simple client-server retrieval system with Linux socket. I've now successfully connect the remote server, but when I close the connection, the server went down, i.e. the server program stopped.
What should I do avoid this?
here's sample of my code:
server:
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netinet/in.h>
int main(void)
{
int optval;
socklen_t optlen = sizeof(optval);
char str[100] = "";
int listen_fd, conn_fd;
struct sockaddr_in servaddr;
listen_fd = socket(AF_INET, SOCK_STREAM, 0);
// check if on
getsockopt(listen_fd, SOL_SOCKET, SO_KEEPALIVE, &optval, &optlen);
printf("keep alive is %s\n", (optval? "ON" : "OFF"));
// set it on
optval = 1;
optlen = sizeof(optval);
setsockopt(listen_fd, SOL_SOCKET, SO_KEEPALIVE, &optval, optlen);
printf("done, check again.\n");
printf("keep alive is %s\n", (optval? "ON" : "OFF"));
bzero( &servaddr, sizeof(servaddr));
// set appropriate protocol and port number (15792)
// the htons() function converts the unsigned short integer
// from host byte order to network byte order.
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htons(INADDR_ANY);
servaddr.sin_port = htons(15792);
// Bind a name to a socket
bind(listen_fd, (struct sockaddr *) &servaddr, sizeof(servaddr));
// listening for incoming connection
listen(listen_fd, 10);
// accept a connection on a socket
conn_fd = accept(listen_fd, (struct sockaddr*) NULL, NULL);
do
{
// set str to null
bzero(str, 100);
// Read from a file descriptor (linux all)
read(conn_fd,str,100);
// print the received message
// printf("Received: %s\n",str);
if (!strcmp(str, "GET TIME\n"))
{
bzero(str, 100);
time_t clocks;
clocks = time(NULL);
sprintf(str, "%s", ctime(&clocks));
write(conn_fd, str, strlen(str));
//close(conn_fd);
}
else
{
bzero(str, 100);
strcpy(str, "ERROR: No such command.\n");
write(conn_fd, str, strlen(str));
//close(conn_fd);
}
} while (1);
}
client:
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc,char **argv)
{
// declare necessary variables
int sockfd;
char recv[1024] = "";
char command[100] = "";
struct sockaddr_in servaddr;
if (argc != 2)
{
printf("usage: %s <ip address>\n", argv[0]);
exit(EXIT_FAILURE);
}
// create a socket with the appropriate protocol
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("ERROR: Failed create cosket.\n");
exit(EXIT_FAILURE);
}
// Set all the socket structures with null values.
bzero(&servaddr, sizeof servaddr);
// set appropriate protocol and port number (1999)
// The htons() function converts the unsigned short integer
// hostshort from host byte order to network byte order.
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(15792);
// Convert IPv4 and IPv6 addresses from text to binary form
if (inet_pton(AF_INET, argv[1], &(servaddr.sin_addr)) <= 0)
{
printf("ERROR: Wrong ip address.\n");
exit(EXIT_FAILURE);
}
// attempt to connect to a socket
if (connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0)
{
printf("ERROR: Failed at connect.\n");
exit(EXIT_FAILURE);
}
else
{
printf("------ connect successfull ------\n");
}
do
{
printf("> ");
fgets(command, 100, stdin);
write(sockfd, command, strlen(command));
if (!strcmp(command, "QUIT\n"))
{
close(sockfd);
break;
}
// print the receive stuff
read(sockfd, recv, sizeof(recv));
fputs(recv, stdout);
bzero(recv, 1024);
} while (1);
}

In your server code, the accept() function must be called in the do-while loop:
// listening for incoming connection
listen(listen_fd, 10);
do
{
// accept a connection on a socket
conn_fd = accept(listen_fd, (struct sockaddr*) NULL, NULL);
...
close(conn_fd);
} while(1);

my question here is, why server ended if I close the connection from
the client.
Because then the blocking read call will return the value 0 indicating the connection was closed, which you promptly ignore. You then try (and fail) to compare the received data (which you have none) to the string and you will attempt to write the error message to the (now disconnected) client which will raise the SIGPIPE error which terminates your application.
– Some programmer dude

Related

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.

UDP Client Server invalid argument

I have a server that is supposed to send information to a client after receiving a message from the client (echo server). Below is the code that is producing an errno 22 which i looked up as "invalid argument". I am trying to understand which argument is invalid because my client sends a message with the same arguments
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
//#include <sys/time.h>
int main(int argc, char *argv[]) {
// port to start the server on
int SERVER_PORT = 8877;
struct timeval server_start, client_start;
// socket address used for the server
struct sockaddr_in server_address;
memset(&server_address, 0, sizeof(server_address));
server_address.sin_family = AF_INET;
// htons: host to network short: transforms a value in host byte
// ordering format to a short value in network byte ordering format
server_address.sin_port = htons(SERVER_PORT);
// htons: host to network long: same as htons but to long
server_address.sin_addr.s_addr = htonl(INADDR_ANY);
// create a UDP socket, creation returns -1 on failure
int sock;
if ((sock = socket(PF_INET, SOCK_DGRAM, 0)) < 0) {
printf("could not create socket\n");
return 1;
}
// bind it to listen to the incoming connections on the created server
// address, will return -1 on error
if ((bind(sock, (struct sockaddr *)&server_address,
sizeof(server_address))) < 0) {
printf("could not bind socket\n");
return 1;
}
// socket address used to store client address
struct sockaddr_in client_address;
int client_address_len = 0;
// run indefinitely
while (true) {
char buffer[500];
printf("problem here \n");
int len=0;
// read content into buffer from an incoming client
if (len = recvfrom(sock, &client_start, sizeof(client_start), 0,(struct sockaddr *)&client_address,&client_address_len)<0){
printf("failed: %d\n", errno);
return 1;
}
// inet_ntoa prints user friendly representation of the
// ip address
//buffer[len] = '\0';
gettimeofday(&server_start);
int send = 0;
// send same content back to the client ("echo")
if(send = sendto(sock, &server_start, sizeof(server_start),0,(struct sockaddr *)&client_address,
&client_address_len)<0){
printf("failed: %d\n", errno);
return 1;
};
}
return 0;
}
I am trying to understand which argument is invalid
No argument is invalid. You got a false positive on your error testing.
if (len = recvfrom(sock, &client_start, sizeof(client_start), 0,(struct sockaddr *)&client_address,&client_address_len)<0){
if(send = sendto(sock, &server_start, sizeof(server_start),0,(struct sockaddr *)&client_address,
&client_address_len)<0){
Usual problem. Operator precedence. Try this:
if ((len = recvfrom(sock, &client_start, sizeof(client_start), 0,(struct sockaddr *)&client_address,&client_address_len))<0){
if((send = sendto(sock, &server_start, sizeof(server_start),0,(struct sockaddr *)&client_address,
&client_address_len))<0){

C - Socket Echo Program

I'm trying to make a program that takes a string from the command line, that is passed in the command line arguments, sends it to the server, then sends it back to the client and displays it on the screen. Right now it is freezing on the server side, from what I can tell using print statements in the recvfrom() function. Does anyone know why it isn't echoing back? For the command line arguments, the server just takes the port number, and the client takes the server name, port number, and string to be echoed back. Below is my code:
Header file:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <errno.h>
#include <signal.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/wait.h>
server.c:
#include "headerFiles.h"
int main(int argc, char* argv[])
{
int s;
int len;
char buffer[256];
struct sockaddr_in servAddr;
struct sockaddr_in clntAddr;
int clntAddrLen;
int serverPort;
// Build local (server) socket address
memset(&servAddr, 0, sizeof(servAddr));
servAddr.sin_family = AF_INET;
servAddr.sin_port = htons(serverPort);
servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
// Create socket
if((s = socket(PF_INET, SOCK_DGRAM, 0)) < 0)
{
perror("Error: socket failed!");
exit(1);
}
// Bind socket to local address and port
if((bind(s, (struct sockaddr*)&servAddr, sizeof(servAddr)) < 0))
{
perror("Error: bind failed!");
exit(1);
}
for(;;) // Runs forever
{
// Receive String
printf("In infinite loop.\n");
len = recvfrom(s, buffer, sizeof(buffer), 0, (struct sockaddr*)&clntAddr, &clntAddrLen);
printf("Received something\n");
// Send String
sendto(s, buffer, len, 0, (struct sockaddr*)&clntAddr, sizeof(clntAddr));
printf("Sent something\n");
}
}
client.c:
#include "headerFiles.h"
int main (int argc, char* argv[]) // Three arguments to be checked later
{
int s; // Socket descriptor
int len; // Length of string to be echoed
char* servName; // Server name
int servPort; // Server port
char* string; // String to be echoed
char buffer[256+1]; // Data buffer
struct sockaddr_in servAddr; // Server socket address
// Check and set program arguments
if(argc != 4)
{
printf("Error: three arguments are needed!\n");
exit(1);
}
servName = argv[1];
servPort = atoi(argv[2]);
string = argv[3];
// Build server socket address
memset(&servAddr, 0, sizeof(servAddr));
servAddr.sin_family = AF_INET;
inet_pton(AF_INET, servName, &servAddr.sin_addr);
servAddr.sin_port = htons(servPort);
// Create socket
if((s = socket(PF_INET, SOCK_DGRAM, 0)) < 0)
{
perror("Error: Socket failed!");
exit(1);
}
// Send echo string
len = sendto(s, string, strlen(string), 0, &servAddr, sizeof(servAddr));
printf("Past sendto\n");
// Receive echo string
recvfrom(s, buffer, len, 0, NULL, NULL);
//Print and verify echoed string
buffer[len] = '\0';
printf("Echo string received: ");
fputs(buffer, stdout);
printf("\n");
// Close the socket
close(s);
// Stop the program
exit(0);
}

C - Sending Modified String Over Sockets

I'm trying to send a modified string over sockets. The goal is to take a string from the client, add something to it, then send it back. The strings are passed in command line arguments. Right now, I can receive the message from the client, but for some reason my recvfrom function is returning -1 which causes the client to get hung up and not receive the sendto from the server. It seems like the server is modifying the string fine, but I can't get it to receive correctly on the other side. I have print statements in my code for testing purposes. The command line arguments for the client are server name, port number, string. The command line arguments for the server are port number, string to concatenate. Below is my code:
headerFiles.h:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <errno.h>
#include <signal.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/wait.h>
server.c:
#include "headerFiles.h"
int main(int argc, char* argv[])
{
int s;
int len;
char buffer[256];
struct sockaddr_in servAddr;
struct sockaddr_in clntAddr;
int clntAddrLen;
int serverPort;
char catStringMeow[256];
serverPort = atoi(argv[1]);
strcpy(catStringMeow, argv[2]);
// Build local (server) socket address
memset(&servAddr, 0, sizeof(servAddr));
servAddr.sin_family = AF_INET;
servAddr.sin_port = htons(serverPort);
servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
// Create socket
if((s = socket(PF_INET, SOCK_DGRAM, 0)) < 0)
{
perror("Error: socket failed!");
exit(1);
}
// Bind socket to local address and port
if((bind(s, (struct sockaddr*)&servAddr, sizeof(servAddr)) < 0))
{
perror("Error: bind failed!");
exit(1);
}
for(;;) // Runs forever
{
printf("buffer = %s\n", buffer);
printf("In for\n");
// Receive String
len = recvfrom(s, buffer, sizeof(buffer), 0, (struct sockaddr*)&clntAddr, &clntAddrLen);
printf("Received %d bytes\n", len);
printf("buffer = %s\n", buffer);
strcat(buffer, " ");
strcat(buffer, catStringMeow);
printf("New string = %s\n",buffer);
printf("buffer size = %d\n", (int)strlen(buffer));
len = (int)strlen(buffer);
// Send String
sendto(s, buffer, len, 0, (struct sockaddr*)&clntAddr, sizeof(clntAddr));
printf("Sent %d bytes\n", len);
}
}
client.c:
#include "headerFiles.h"
int main (int argc, char* argv[]) // Three arguments to be checked later
{
int s; // Socket descriptor
int len; // Length of string to be echoed
char* servName; // Server name
int servPort; // Server port
char* string; // String to be echoed
char buffer[256+1]; // Data buffer
struct sockaddr_in servAddr; // Server socket address
// Check and set program arguments
if(argc != 4)
{
printf("Error: three arguments are needed!\n");
exit(1);
}
servName = argv[1];
servPort = atoi(argv[2]);
string = argv[3];
// Build server socket address
memset(&servAddr, 0, sizeof(servAddr));
servAddr.sin_family = AF_INET;
inet_pton(AF_INET, servName, &servAddr.sin_addr);
servAddr.sin_port = htons(servPort);
// Create socket
if((s = socket(PF_INET, SOCK_DGRAM, 0)) < 0)
{
perror("Error: Socket failed!");
exit(1);
}
// Send echo string
len = sendto(s, string, strlen(string), 0, (struct sockaddr*) &servAddr, sizeof(servAddr));
printf("Sent %d bytes\n", len);
// Receive echo string
len = recvfrom(s, buffer, len, 0, NULL, NULL);
printf("Received\n");
//Print and verify echoed string
buffer[len] = '\0';
printf("Echo string received: ");
fputs(buffer, stdout);
printf("\n");
// Close the socket
close(s);
// Stop the program
exit(0);
}
do
// Receive echo string
len = recvfrom(s, buffer, sizeof(buffer), 0, NULL, NULL);
printf("Received\n");
and make buffer bigger.
You're passing an uninitizlied clntAddrLen value to recvfrom, which is resulting in the Invalid argument error code. According to the documentation:
The argument addrlen is a value-result argument, which the caller should initialize before the call to the size of the buffer associated with src_addr, and modified on return to indicate the actual size of the source address.
So you need to initialize it with:
clntAddrLen = sizeof(clntAddr);
Make sure you initialize the client address length variable before using it in sendto or recvfrom.
The problem is that on the first calling to sendto from client.c, the servers sees the client's ip as 0.0.0.0, after that on the second, third,... calls the client.c get an ip and have a legal ip such as 127.0.0.3:3212.
You can see that second, third, ... clients work.
Initialize length variable to sizeof(struct sockaddr_in)

server recieving some junk value from the client?

#include <windows.h>
#include <stdio.h>
#include <string.h>
#include <winsock.h>
#pragma once
#pragma comment (lib, "ws2_32.lib")
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <time.h>
#include <winsock.h>
#include <io.h>
SOCKET sock;
SOCKET fd;
char recv_data[10];
int port = 18001;
void CreateSocket()
{
struct sockaddr_in server, client; // creating a socket address structure: structure contains ip address and port number
printf("Initializing Winsock\n");
WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested = MAKEWORD (1, 1);
if (WSAStartup (wVersionRequested, &wsaData) != 0){
printf("Winsock initialised failed \n");
} else {
printf("Initialised\n");
}
// create socket
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock < 0) {
printf("Could not Create Socket\n");
//return 0;
}
printf("Socket Created\n");
// create socket address of the server
memset( &server, 0, sizeof(server));
// IPv4 - connection
server.sin_family = AF_INET;
// accept connections from any ip adress
server.sin_addr.s_addr = htonl(INADDR_ANY);
// set port
server.sin_port = htons(port);
//Binding between the socket and ip address
if(bind (sock, (struct sockaddr *) &server, sizeof(server)) < 0)
{
printf("Bind failed with error code: %d", WSAGetLastError());
}
//Listen to incoming connections
if(listen(sock,3) == -1){
printf("Listen failed with error code: %d", WSAGetLastError());
}
printf("Server has been successfully set up - Waiting for incoming connections");
int len;
len = sizeof(client);
fd = accept(sock, (struct sockaddr*) &client, &len);
if (fd < 0){
printf("Accept failed");
}
//echo(fd);
printf("\n Process incoming connection from (%s , %d)", inet_ntoa(client.sin_addr),ntohs(client.sin_port));
//closesocket(fd);
}
int main()
{
CreateSocket();
while(1)
{
if(fd == -1)
{
printf("socket error\n");
}
else
{
recv(fd, recv_data, 9, 0);
printf("value is %s", recv_data);
}
}
return 0;
}
The above is a server code : I am creating a socket and accepting the data from the client. The client is sending a data and the server is accepting it.
If the client sends a to the server then the server will add some junk characters to it. If the client sends 4 characters then it will receive all the four characters. if the client sends one or two characters :Why the server is receiving some junk value ??
This is because, recv does not append NULL character at the end of the string. You have to explicitly add the NULL character. So, use return value of recv call and use it to append the NULL character.
int retval;
retval = recv(fd, recv_data, 9, 0);
if(retval != SOCKET_ERROR) {
recv_data[retval] = '\0';
printf("value is %s", recv_data);
}
'\0' is the only character which will differ you from char array and string.
Since you are using %s to print the string it is necessary to add the '\0' character at the end.

Resources