message from client to server in C - 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.

Related

Server not accepting connecting to client

I'm trying to make a simple Socket program and I'm right now able to create a server socket, bind the server socket to a port and listen for incoming connections after which, when I try to start with the accepting of the connection, nothing gets printed out.
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char *argv[]){
char buffer[1024] = {0};
char *mes = "peepeepoopoo";
struct sockaddr_in server;
int addr_size = sizeof(server);
//xxxxxxxx Creating the socket xxxxxxxx
int sockfd_server = socket(AF_INET, SOCK_STREAM, 0);
int client_socket;
if(sockfd_server < 0){
printf("Socket not created\n");
return -1;
}
puts("Socket created\n");
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(8070);
//xxxxxxxx Binding xxxxxxx
if(bind(sockfd_server,(struct sockaddr*)&server, sizeof(server)) < 0){
printf("failed to bind\n");
return -1;
}
puts("binding completed\n");
//xxxxxxxx Listening xxxxxxxx
if (listen(sockfd_server,3) < 0)
{
printf("Listening error\n");
}
puts("Listening\n");
// none of the statements prints, almost like its frozen.
int new_Socket = accept(sockfd_server, (struct sockaddr*)&server, (socklen_t*)&addr_size);
if(new_Socket < 0){
printf("could not accept socker\n");
return -1;
}
puts("accepted\n");
int val = read(new_Socket,buffer, 1024);
printf("%s\n",buffer);
send(new_Socket, mes, strlen(mes), 0);
return 0;
}
What do I do to fix this?
accept
If no pending connections are present on the queue, and the socket is not marked as nonblocking, accept() blocks the caller until a connection is present.
Question: Do you connect a client to your server?
addr_size is declared as int, yet passed as an argument while casting it to socklen_t. Can you guarantee that sizeof(int) == sizeof(socklen_t)?
You read into buffer but do not null-terminate it before passing it to printf with the format specifier %s.

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 - 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)

Linux C socket - keep server alive

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

Passing multiple messages from client -> server and server -> client sockets in C

Could someone help identify why my server cannot accept more than one message from the client?
I am attempting to have the flow be like the following:
1. Client sends size of message to server
2. Server receives the size and sends a response back. In this case 0.
3. Client checks response and then writes message to server.
4. Server reads message and prints it out.
The problem I am getting is that the accept() at step 4 is never unblocking.
CLIENT
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
int main(int argc, char *argv[])
{
int sock = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in s_address;
s_address.sin_family = AF_INET;
s_address.sin_port = htons(51717);
s_address.sin_addr.s_addr = INADDR_ANY;
if (connect(sock, (struct sockaddr *) &s_address, sizeof(s_address)) < 0) {
printf("ERROR: Cannot connect()\n");
exit(0);
}
char *org_msg = "Hello";
printf("Writing size of Hello\n");
char msg1[1];
msg1[0] = sizeof(org_msg);
write(sock, msg1, sizeof(msg1));
printf("Waiting for response from server\n");
struct sockaddr_in c_address;
socklen_t c_length = sizeof(c_address);
int new_sock = accept(sock, (struct sockaddr *) &c_address, &c_length);
printf("Reading response from server\n");
char stat[1];
read(new_sock, stat, 1);
if (atoi(stat) == 0) {
printf("Writing Hello to server\n");
write(sock, org_msg, sizeof(org_msg));
}
close(sock);
close(new_sock);
}
SERVER
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
int main(int argc, char *argv[])
{
int sock = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in s_address;
s_address.sin_family = AF_INET;
s_address.sin_port = htons(51717);
s_address.sin_addr.s_addr = INADDR_ANY;
if (bind(sock, (struct sockaddr *) &s_address, sizeof(s_address)) < 0) {
printf("ERROR: Cannot bind()\n");
exit(0);
}
listen(sock, 3);
printf("Waiting for client message\n");
struct sockaddr_in c_address;
socklen_t c_length = sizeof(c_address);
int new_sock = accept(sock, (struct sockaddr *) &c_address, &c_length);
printf("Reading client message\n");
char msg[1];
read(new_sock, msg, 1);
printf("Writing response to client\n");
char stat[1];
stat[0] = '0';
write(new_sock, stat, sizeof(stat));
printf("Waiting for client message\n");
int new_sock2 = accept(sock, (struct sockaddr *) &c_address, &c_length);
printf("Reading client message\n");
char msg2[atoi(msg)];
read(new_sock2, msg2, sizeof(msg2));
printf("MESSAGE: %s\n", msg2);
close(sock);
close(new_sock);
close(new_sock2);
}
You should not call accept() on an already-connected socket. Once you have a connected socket in the server (the socket returned by accept()) you should just keep reading and writing that socket until the connection is closed. The steps for the server should be similar to:
listen_socket = socket(...);
listen(listen_socket, ...);
connected_socket = accept(listen_socket, ...);
read(connected_socket, ...)
write(connected_socket, ...)
read(connected_socket, ...)
write(connected_socket, ...)
...
Similarly the client should just keep reading and writing the socket once it has been connected successfully - the steps for the client should be:
connected_socket = socket(...);
connect(connected_socket, ...);
write(connected_socket, ...);
read(connected_socket, ...);
write(connected_socket, ...);
read(connected_socket, ...);
...
INADDR_ANY works in the server but your client needs to specify what host it's connecting to.
If both are on the same machine, just use 127.0.0.1 or localhost (you'll have to do a transform so that it's the right format)
More information here, but a short answer would be
#define INADDR_LOOPBACK 0x7f000001
and then s_address.sin_addr.s_addr = htonl (INADDR_LOOPBACK)
On the client you try to accept a new connection with the socket you previously connected to the server, which will be bound to a system-chosen port number. The server never tries to connect to the client, so the accept call on the client never returns (actually it may return but with an error, because you never call listen on that socket).
Why not just perform step 3 with the same socket used in the previous steps? If for some reason you do need a new socket, you should create a new socket in the client instead of reusing the previous socket (or call close on the previous socket and then call connect on it again).
BTW if all you need is IPC, sockets are a really bad way to do it. I suggest something like Java RMI.

Resources