Write to remote file using TCP - c

I am working on a server/client program for a project, for it to be able to work properly I need to use fopen and fprintf on the client. The server is going to take realtime data output from a USB joystick (the axis rotations) and send that information via TCP to the client which in turn writes that information to a file. I have followed THIS tutorial to get the TCP setup and its working perfectly. I am able to send messages from the server to the client. How can I take a command such as fprintf(fp, "2=%d\n", zAxis) from the server and send it to the client to be wrote to a file? Maybe I am overlooking something simple to accomplish this. I don't know where to begin, if I can send the zAxis variable from the server to the client I think I can figure it out from there.
Here is my code
SERVER.C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#define PORTNUM 2343
int main(int argc, char *argv[])
{
char msg1[10];
printf("Please enter info\n");
fgets(msg1, 20, stdin);
struct sockaddr_in dest; /* socket info about the machine connecting to us */
struct sockaddr_in serv; /* socket info about our server */
int mysocket; /* socket used to listen for incoming connections */
socklen_t socksize = sizeof(struct sockaddr_in);
memset(&serv, 0, sizeof(serv)); /* zero the struct before filling the fields */
serv.sin_family = AF_INET; /* set the type of connection to TCP/IP */
serv.sin_addr.s_addr = htonl(INADDR_ANY); /* set our address to any interface */
serv.sin_port = htons(PORTNUM); /* set the server port number */
mysocket = socket(AF_INET, SOCK_STREAM, 0);
/* bind serv information to mysocket */
bind(mysocket, (struct sockaddr *)&serv, sizeof(struct sockaddr));
/* start listening, allowing a queue of up to 1 pending connection */
listen(mysocket, 1);
int consocket = accept(mysocket, (struct sockaddr *)&dest, &socksize);
while(consocket)
{
printf("Incoming connection from %s - sending welcome\n", inet_ntoa(dest.sin_addr));
send(consocket, msg1, strlen(msg1), 0);
consocket = accept(mysocket, (struct sockaddr *)&dest, &socksize);
}
close(consocket);
close(mysocket);
return EXIT_SUCCESS;
}`
CLIENT.C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#define MAXRCVLEN 500
#define PORTNUM 2343
int main(int argc, char *argv[])
{
char buffer[MAXRCVLEN + 1]; /* +1 so we can add null terminator */
int len, mysocket;
struct sockaddr_in dest;
mysocket = socket(AF_INET, SOCK_STREAM, 0);
memset(&dest, 0, sizeof(dest)); /* zero the struct */
dest.sin_family = AF_INET;
dest.sin_addr.s_addr = inet_addr("192.168.254.16"); /* set destination IP number */
dest.sin_port = htons(PORTNUM); /* set destination port number */
connect(mysocket, (struct sockaddr *)&dest, sizeof(struct sockaddr));
len = recv(mysocket, buffer, MAXRCVLEN, 0);
/* We have to null terminate the received data ourselves */
buffer[len] = '\0';
printf("Received %s (%d bytes).\n", buffer, len);
close(mysocket);
return EXIT_SUCCESS;
}

Related

Infinite waiting during recvfrom() UDP server and client

I'm trying to learn UDP on C.
My goal is to send a message in console, in the client consol to the server, and sending the exact same message from the server to the client.
When I send a message from client to server, I do receive it, but the opposit is not working, and the waiting is infinite.
I don't have any problem in console.
The weird thing is that i'm using the exact same methode to send both messages.
Here's my client, Thanks to everyone helping me :)
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define PORT 8080
#define BUFSIZE 4096
// Driver code
int main(int argc, char *argv[]) {
char buffer[BUFSIZE];
struct sockaddr_in servaddr, cliaddr;
int len, n;
char *adresse= argv[1];
if (argc<1){
perror("nb args not enough");
exit(EXIT_FAILURE);
}
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr(adresse);
servaddr.sin_port = htons(PORT);
// Socket()
int udp_server = socket(AF_INET, SOCK_DGRAM, 0) ;
if(udp_server<0){
perror("socket creation failed \n");
exit(EXIT_FAILURE);
}
// Bind())
int errBind = bind(udp_server, (const struct sockaddr *)&servaddr, sizeof(servaddr));
if(errBind<0){
perror("errBind \n" );
exit(EXIT_FAILURE);
}
// recvfrom()
n = recvfrom(udp_server, (char *)buffer, BUFSIZE,0, ( struct sockaddr *) &cliaddr,&len);
if (n<0){
perror("recvfrom error\n" );
exit(EXIT_FAILURE);
}
buffer[n] = '\0';
printf("CLIENT: %s\n", buffer);
char *message ="caca";
sendto(udp_server, (const char *)message, strlen(message),
0, (const struct sockaddr *) &cliaddr,
len);
close(udp_server);
//////////////////////////This part below is never reached
printf("end");
return 0;
}
Also here's my server:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define PORT 8080
#define BUFSIZE 4096
// Driver code
int main(int argc, char *argv[]) {
char buffer[BUFSIZE];
// char *message = "AAAAAAAAAAAAAAAAAA";
struct sockaddr_in servaddr, cliaddr;
int len, n;
char *adresse= argv[1];
if (argc<1){
perror("nombre d'arguments insuffisents, veuillez entrer :\n ./serveur port_serveur \n");
exit(EXIT_FAILURE);
}
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr(adresse);
// servaddr.sin_addr.s_addr = INADDR_ANY;
servaddr.sin_port = htons(PORT);
// Socket()
int udp_server = socket(AF_INET, SOCK_DGRAM, 0) ;
if(udp_server<0){
perror("socket creation failed \n");
exit(EXIT_FAILURE);
}
// Bind())
int errBind = bind(udp_server, (const struct sockaddr *)&servaddr, sizeof(servaddr));
if(errBind<0){
perror("errBind \n" );
exit(EXIT_FAILURE);
}
// recvfrom()
n = recvfrom(udp_server, (char *)buffer, BUFSIZE,0, ( struct sockaddr *) &cliaddr,&len);
if (n<0){
perror("recvfrom error\n" );
exit(EXIT_FAILURE);
}
buffer[n] = '\0';
printf("CLIENT: %s\n", buffer);
int l = sendto(udp_server, (const char *)buffer, strlen(buffer),
0, (const struct sockaddr *) &servaddr,
sizeof(servaddr));
close(udp_server);
printf("end");
//////////////// This is reached
return 0;
}
There are several issues. The main issue is that both the client and server first tries to receive, then send. Thus they cannot both receive the message from the other party. Also, the client need not explicitly bind the socket.
In principle, the client must know the server address, but the server does not know the client address. Hence, the flow of communication must be that the client first sends a message to the server which will make the client known to the server. The server can then send a message to the address of the client.
In summary, the server should:
Create socket
Bind socket
Wait for message (recvfrom())
Send message to sender of the received message (sendto())
Close socket
The client should:
Create socket
Send message to the server (sendto())
Wait for message (recvfrom())
Close socket

How to create a multi client on one server system with fork() on c

Here is the code TCP/IP client – server. The program works like this, first is the client which connect with server and printf hello. The server on the another side if the connection has successfully done printf a msg for connection with the port. So my question is how to use fork() function on server to create a multi clients system with one server.
// client.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define SIZE 1024
int main(int argc, char *argv [])
{
int sock, i=1 ;
char msg[SIZE],reply[SIZE];
struct sockaddr_in addr; // Internet socket
addr.sin_family = AF_INET; // Internet socket opou exei thn oikogeneia address IP kai provides the communication of server-client
inet_aton(argv [1], &addr.sin_addr);
addr.sin_port = htons(atoi(argv[2]) ) ; // metatroph byte pc se byte IP
sock = socket(AF_INET, SOCK_STREAM, 0); // Stream socket kanei to connection creat one " file descriptor " ppou omos den einai akoma etoimos gia thn epikinonia
connect(sock, ( struct sockaddr *)&addr, sizeof(addr)); // the last step and the finally connection from one socket to another client-server
prontf("hello");
strcpy(msg,"") ;
strcpy(reply,"");
close(sock);
return 0;
}
// server.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define SIZE 1024
#define STR_SIZE 100 //STR_SIZE doesn't have to be a constant
int main(int argc, char *argv [])
{
int psock, sock,cli_addr_len,i,j,res1;
char msg[SIZE];
struct sockaddr_in addr,cli_addr; // Internet socket
char reply[SIZE];
memset(&cli_addr, 0, sizeof(cli_addr));
cli_addr_len = sizeof(cli_addr);
addr.sin_family = AF_INET; // Internet socket
addr.sin_addr.s_addr = htonl(INADDR_ANY); // All interfaces
addr.sin_port = htons(atoi(argv [1]) ) ;
psock = socket(AF_INET, SOCK_STREAM, 0); // Stream socket
bind(psock, ( struct sockaddr *)&addr, sizeof(addr)); // assigning a name to a sock
listen (psock, 1) ;
strcpy(msg,"") ;
printf("\n waiting for new connection (port : %s) ... \n", argv [1]);
sock = accept(psock, (struct sockaddr *)&cli_addr, &cli_addr_len); // accept and take request - sock from the queue to connection
printf("connection established...\n");
close(sock);
}

I got some strange word 'Received: 艎��' in socket program

I wrote a server program and a client program that communicate with sockets on linux ubuntu. The client program outputs Received: 艎��
This my server code:
/*** tcp_server.c ***/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
int main() {
int sock_fd, new_fd, bytes;
struct sockaddr_in seraddr, cliaddr;
char data[1024];
socklen_t cli_addr_size;
cli_addr_size = sizeof(cliaddr);
sock_fd = socket(AF_INET, SOCK_STREAM, 0);
memset(&seraddr, 0, sizeof(seraddr));
seraddr.sin_family = AF_INET;
seraddr.sin_addr.s_addr = htonl(INADDR_ANY); // INADDR_ANY : It received Network Interface that connected server defined interface, htonl :
seraddr.sin_port = htons(5050);
bind(sock_fd, (struct sockaddr *)&seraddr, sizeof(seraddr));
listen(sock_fd, 10);
while (1) {
new_fd = accept(sock_fd, (struct sockaddr *)&cliaddr, &cli_addr_size);
bytes = recv(new_fd, data, 1024, 0);
send(new_fd, data, bytes, 0);
close(new_fd);
}
close(sock_fd);
}
My client code is:
/*** tcp_client.c ***/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
int main(int argc, char *argv[]) {
int sock_fd, bytes;
struct sockaddr_in ser_addr;
char *snddata, rcvdata[1024];
snddata = argv[2];
sock_fd = socket(AF_INET, SOCK_STREAM, 0);
memset(&ser_addr, 0,sizeof(ser_addr));
ser_addr.sin_family = AF_INET;
ser_addr.sin_addr.s_addr = inet_addr(argv[1]); // INADDR_ANY : It received Network Interface that connected server defined interface, htonl :
ser_addr.sin_port = htons(5050);
connect(sock_fd, (struct sockaddr *)&ser_addr, sizeof(ser_addr));
send(sock_fd, snddata, strlen(snddata), 0);
printf("Received: ");
bytes = recv(sock_fd, rcvdata, 1024, 0);
rcvdata[bytes] = '\0';
printf("%s\n", rcvdata);
close(sock_fd);
}
First I got an error for argument 3 of accept, then I changed
new_fd = accept(sock_fd, (struct sockaddr *)&cliaddr, sizeof(cliaddr);
But It still produces this strange word.
Try to change your send() and receive() functions so that you have full control over how much and which byte you send from the buffer (data[1024]) like in this thread : C socket: recv and send all data and also see Beej's Guide to Network Programming (http://beej.us/guide/bgnet/)
Also make sure that you initialize your data buffers:
data[1024] = "";
rcvdata[1024] = "";
or
data[1024];
data[0] = '\0';
rcvdata[1024];
rcvdata[0] = '\0';
, background is in this thread : Why I am getting this unusually symbols by printing char string

When requesting time from server I get a Segmentation fault (core dumped). How can I resolve this?

I am writing a program where the client sends the server a time request. I also want to send my name and get the server to echo it back. So far the program will echo my name but then I get a Segmentation fault (core dumped) where the time should be display. I have attached the code for the clien and server and also a screenshot of the terminal.
SERVER CODE
#include <stdio.h> /* I/O functions */
#include <string.h> /* string functions */
#include <stdlib.h> /* C standard functions */
#include <sys/socket.h> /* socket functions */
#include <sys/types.h> /* library of basic types */
#include <netinet/in.h> /* library of Internet address functions */
#include <arpa/inet.h> /* Internet operations */
#include <time.h> /* time functions */
#define PORT 8080 /* server port # */
#define BUFFSIZE 200 /* buffer size */
int main()
{
int sockfd;
int addrlen;
char buffer[BUFFSIZE];
struct sockaddr_in server;
struct sockaddr_in client;
time_t current_time;
/* Populate socket data structures with IP address and port number */
memset((char *) &server, 0, sizeof(struct sockaddr_in));
server.sin_family = AF_INET;
server.sin_port = htons(PORT);
/* Create a UDP socket; returns -1 on failure */
sockfd = socket(AF_INET,SOCK_DGRAM,0);
if (sockfd == -1) {
printf("Socket error\n");
exit(1); /* Exit on error */
}
/* Bind the socket address */
if ((bind(sockfd,(struct sockaddr*)&server,sizeof(struct sockaddr_in))) == -1) {
printf("Server bind error\n");
exit (1); /* Exit on error */
}
/* Status message */
printf("The server is listening on port: %d\n", PORT);
printf("Waiting for client request...\n");
printf("Press CTRL + C to exit\n");
while(1) {
addrlen = sizeof(struct sockaddr_in);
recvfrom(sockfd, buffer,BUFFSIZE, 0,(struct sockaddr *)&client, (socklen_t *)&addrlen);
current_time = time(NULL);
memcpy(buffer + strlen(buffer) + 1, &current_time, sizeof(current_time));
sendto(sockfd, buffer, strlen(buffer) + 1 + sizeof(current_time), 0, (struct sockaddr *)&client, addrlen);
}
exit(0);
} /* End of time server program */
CLIENT CODE
#include <stdio.h> /* I/O functions */
#include <string.h> /* string functions */
#include <stdlib.h> /* C standard functions */
#include <sys/socket.h> /* socket functions */
#include <sys/types.h> /* library of basic types */
#include <netinet/in.h> /* library of Internet address functions */
#include <arpa/inet.h> /* Internet operations */
#include <time.h> /* time functions */
#define BUFFSIZE 200 /* buffer size */
int main(int argc, char *argv[])
{
int sockfd;
int addrlen;
char buffer[BUFFSIZE] = "GET TIME\r\n";
struct sockaddr_in server;
struct sockaddr_in client;
char *servIP = argv[1]; // Server IP address from command line
int servPort = atoi(argv[2]); // Server port number from command line
char *name = argv[3];
time_t current_time;
/* Check that two arguments were passed on the command line */
if (argc != 4) {
printf("Usage: udp-time-client [IP address] [Port] [Name] \n");
exit(1);
}
/* Populate server socket data structure with IP address and port number */
memset((char *) &server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(servPort);
server.sin_addr.s_addr = inet_addr(servIP);
/* Populate client socket data structure with IP address and port number */
memset((void *)&client, '\0', sizeof(client));
client.sin_family = AF_INET;
client.sin_port = htons(servPort);
client.sin_addr.s_addr = inet_addr(servIP);
/* Create a UDP socket; returns -1 on failure */
sockfd = socket(AF_INET,SOCK_DGRAM,0);
if (sockfd == -1) {
printf("Socket error\n");
exit(1);
}
/* Status message */
printf("Client is sending on IP address %s port: %d\n", servIP, servPort);
/* Send the time request to the server */
addrlen = sizeof(struct sockaddr_in);
strcpy(buffer, name);
sendto(sockfd, buffer, (int)strlen(buffer) + 1, 0, (struct sockaddr *)&server, addrlen);
printf("Request sent to server\n");
/* Receive the time request from server */
recvfrom(sockfd, (char *) buffer, sizeof(buffer), 0, (struct sockaddr *)&server, (socklen_t *)&addrlen);
/* Print the name received from the server */
printf("\n The name received from the server:%s\n", buffer);
memcpy((void *)current_time, buffer + strlen(buffer) + 1, sizeof(current_time));
/* Print the time received from the server */
printf("\n The time received from the server:%s\n", ctime(&current_time));
exit(0);
} /* End of time client program */
Screenshot of terminal As you can see, my name is echoed back but I get the error where the time should be
memcpy((void *)current_time, ...);
should be
memcpy(&current_time, ...);

UDP Client Segmentation Error

Please help! This is due in a few hours and I've had no luck w/ online searches
CODE:
/*
Description:
The client should first send a datagram to the LocationServer.
The LocationServer will be listening on port number 23510 of the host c-lnx001.engr.uiowa.edu.
The message contained in this datagram should be the specified UserID (no null characters, blanks, line-feeds, or other extraneous characters).
The LocationServer will respond with a datagram containing the following information:
[WeatherServer hostname] [WeatherServer port #]
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h> /* for fprintf */
#include <string.h> /* for memcpy */
#include <strings.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdlib.h>
#define SIZE 2048
int main(){
struct hostent *hp; /* host information */
struct sockaddr_in servaddr; /* server address */
char *my_message = "laura\0";/*USERID as message to server*/
char *buf_addr;
char *host = "c-lnx001.engr.uiowa.edu\0";
int port = 23510;
int fd;
/* fill in the server's address and data */
//memset((char*)&servaddr, 0, sizeof(servaddr)); ?
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(23510);
/* look up the address of the server given its name */
hp = gethostbyname("c-lnx001.engr.uiowa.edu");
if (!hp) {
fprintf(stderr, "could not obtain address of %s\n", host);
return 0;
}
/* put the host's address into the server address structure */
// DOESN't WORK: memcpy((void *)&servaddr.sin_addr, hp->h_addr_list[0], hp->h_length);
bcopy(hp->h_addr,(char*)&servaddr.sin_addr,hp->h_length);
if((fd = socket(AF_INET,SOCK_DGRAM, 0))<0)
{
exit(2);
}
/* send a message to the server */
if (sendto(fd, my_message, strlen(my_message), 0, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0)
{
perror("sendto failed");
return 0;
}
int addrlen = sizeof(servaddr);
recvfrom(fd,buf_addr,SIZE,0,(struct sockaddr*)&servaddr,&addrlen);
printf("%s\n", buf_addr);
}
I think your problem is that you're not resetting the serveraddr
Here's a working copy
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define IP_ADDRESS "127.0.0.1"
#define SERVER_PORT 5060
int main (int argc, char *argv[])
{
int recBytes, clientSocket=socket(AF_INET, SOCK_DGRAM, 0);
char buf[80], msg[]="greeting to server";
const int msgLen = sizeof(msg);
struct sockaddr_in serverAddr;
socklen_t reSize;
memset(&serverAddr, sizeof(struct sockaddr_in), 0);
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(SERVER_PORT);
inet_aton(IP_ADDRESS, &serverAddr.sin_addr);
if(sendto(clientSocket, msg, sizeof(msg), 0, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) != (sizeof(msg)))
{
perror("sendto");
return -1;
}
reSize = sizeof(struct sockaddr);
if((recBytes = recvfrom(clientSocket, buf, sizeof(buf)-1, 0, (struct sockaddr*)&serverAddr, &reSize)) == -1)
{
perror("recvfrom");
return -1;
}
buf[recBytes]='\0';
printf("%s\n", buf);
return 0;
}

Resources