Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I'm using this command to compile:
gcc –Werror –std=c99 client.c –o client
CODE:
#include <string.h>
#include <stdio.h>
#include <strings.h>
#include <stdlib.h>
#include <unistd.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define BUFFER_SIZE 1000
#define PORT_NUM 8888
void error(char *msg)
{
perror(msg);
exit(0);
}
int main(int argc, char *argv[])
{
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[BUFFER_SIZE];
if (argc < 3) {
fprintf(stderr,"usage %s hostname port\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");
while (1)
{
bzero(buffer, BUFFER_SIZE);
fgets(buffer, BUFFER_SIZE, stdin);
if((strncmp(buffer,"close",5) == 0 ))
break;
printf("Please enter the message: ");
bzero(buffer, BUFFER_SIZE);
n = write(sockfd,buffer,strlen(buffer));
if (n < 0)
error("ERROR writing to socket");
bzero(buffer, BUFFER_SIZE);
n = read(sockfd,buffer, BUFFER_SIZE-1);
if (n < 0)
error("ERROR reading from socket");
printf("%s\n",buffer);
}
close(sockfd);
return 0;
}
Trying to compile it in a shell on VM whos OS is linux
This error is driving me crazy, I don't understand what to do inorder to fix this.
I thought the client.c file is damaged, so I copied and pasted into a new .c file. When that failed, I wrote it from 0 and still getting this error.
Thanks in advance!
Text processing programs don't always agree on whether a \n character is line separator or line terminator - the difference being whether or not the last line in a file should be followed by a \n character or not.
I've never seen GCC complain about this, but you didn't indicate where the error is actually coming from.
You should be able to correct the situation by simply pressing ENTER after the last line in your file.
Alternatively, you could open, and them save the file using an editor like Vim, which considers it a line terminator.
As a matter of comparison, most UNIX tools also consider \n a line terminator, and include it after the final line. This allows one to cat a file without corrupting whatever follows (e.g. another file, the shell prompt, etc.)
Add Enter (new line) behind the closing bracket.
Related
server.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <unistd.h>
void error(char *msg)
{
perror(msg);
exit(1);
}
int main(int argc, char *argv[])
{
int sockfd, newsockfd, portno, clilen;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
int n;
char *result1 = "Ian G. Harris";
char *result2 = "Joe Smith";
char *result3 = "Jane Smith";
if (argc < 2)
{
fprintf(stderr,"ERROR, no port provided\n");
exit(1);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
error("ERROR opening socket");
}
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr,
sizeof(serv_addr)) < 0)
error("ERROR on binding");
listen(sockfd,5);
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0)
{
error("ERROR on accept");
}
while (strcmp(buffer, "+++") != 0)
{
bzero(buffer,256);
n = read(newsockfd,buffer,255);
if (n < 0) error("ERROR reading from socket");
printf("Address server started\n");
if (strcmp(buffer, "harris#ics.uci.edu\n") == 0)
{
printf("%s\n", result1);
}
else if(strcmp(buffer, "joe#cnn.com\n") == 0)
{
printf("%s\n", result2);
}
else if(strcmp(buffer, "jane#slashdot.org\n")==0)
{
printf("%s\n", result3);
}
}
return 0;
}
client.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
void error(char *msg)
{
perror(msg);
exit(0);
}
int main(int argc, char *argv[])
{
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[256];
if (argc < 3)
{
fprintf(stderr,"usage %s hostname port\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
server = gethostbyname(argv[1]);
if (server == NULL)
{
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");
while (strcmp(buffer, "+++") != 0)
{
printf("> ");
bzero(buffer,256);
fgets(buffer,255,stdin);
n = write(sockfd,buffer,strlen(buffer));
if (n < 0)
error("ERROR writing to socket");
bzero(buffer,256);
n = read(sockfd,buffer,255);
if (n < 0)
error("ERROR reading from socket");
printf("%s\n",buffer);
}
return 0;
}
I am new to c and I am writing a server.c and client.c. The problem of my code is that I cannot make the program keep taking inputs until I enter "+++" to quit. The correct output is shown below:
client terminal:
> harris#ics.uci.edu
Ian G. Harris
> joe#cnn.com
Joe
>
server terminal:
Address server started
harris#ics.uci.edu
joe#cnn.com
in my code, when I enter "harris#ics.uci.edu" in client terminal, it does the following:
> harris#ics.uci.edu
(empty line)
and it does not take any input anymore.
Is there something wrong in the while loop? can someone help me to fix it? Thanks in advance.
Few things:
In the client loop, you do a write and a read on the socket. But your server never writes to that socket(no write call in the server, only read). As a result, your client gets blocked on the read call. That's why you cannot enter more...
In general, you need to check how much you wrote in and keep writing until done (a loop is needed).
int n = 0;
while (n != strlen(buffer){
n += write(sockfd,&buffer[n],strlen(buffer)-n);
}
Same goes for reading from a socket:
int n = 0;
while (n != strlen(buffer){
n += read(sockfd,&buffer[n],strlen(buffer)-n);
}
Here's what I believe is likely happening.
Client sends some chunk of data. Possibly all of the string harris#ics.uci.edu, but possibly less.
The server reads some chunk of this, most likely less than the full string, say harris#ic.
The server performs the strcmp, which doesn't match anything, so returns to the top of the loop.
The server reads the remainder of the email, say s.uci.edu into buffer, thus overwriting it.
Again, this doesn't match anything, so the server goes to the top of the while loop again.
The server hangs on the read call, waiting for data from the client. Because the client is waiting for a reply, it's stuck on its own read call. ...And nothing else happens.
There are two main problems here. First, TCP sockets are just streams of bytes, and when you read data from them, the OS no longer keeps it around. You are now expected to handle any previously- or partially-read data if you need. And second, the OS often transmits (both sending and receiving) fewer bytes than you request. While you ask that the full string harris#ics.uci.edu be sent, only a portion of that may be sent, or only a portion of that may be read on the other side.
This means two things for you. It's always important to check the amount of data read/written any time you call read(2) or write(2), but it's crucial in networking. Make sure you read/write as much as you need (the full email in this case) before moving on to, for example, waiting for a reply.
The second thing is that you need some way of delineating full messages and buffering partial messages. In what you've got, as is common in lots of text-based messaging protocols, the newline \n is your delimiter. So instead of a single call to read(2) in the server, you need something like this (pseduocode):
while newline not in data:
data += read(sockfd, ...)
Once you receive your newline, process the full message, but don't throw away any extra bytes you've read from the next message. Keep those around, and append the next bytes read from the socket to them, and so on.
EDIT:
Note that it's usually better to use recv(2) and send(2) when working with sockets. The read(2)/write(2) system calls will work just fine, but the others are more clear when working with sockets, and allow you to specify other flags, for example, peeking at the bytes currently on the socket or waiting until all the bytes you request are available before returning.
I have made small server and client programs to compare time taken for udp and tcp. So I have made a while loop for sending 100 messages. What the problem seems to be is that presence of loop in tdp client causes program to stop execution after certain line. The debug lines are also not being executed. I have never seen this kind of behaviour.
I expect the loop to exeute 100 times and output the time taken for those loops. But the otput is just
Connection to server:port 127.0.0.1:55057
/* usage: ./tcpclient host port */
#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 <netdb.h>
#include <time.h>
#include <arpa/inet.h>
#define BUFSIZE 1024
void error(char *msg) {
perror(msg);
exit(0);
}
int main(int argc, char **argv) {
int sockfd, portno, n;
struct sockaddr_in serveraddr;
struct hostent *server;
char *hostname;
char buf[BUFSIZE];
strcpy(buf, "hello");
clock_t start; int count=0;
/* check command line arguments */
if (argc != 3) {
fprintf(stderr,"usage: %s <hostname> <port>\n", argv[0]);
exit(0);
}
hostname = argv[1];
portno = atoi(argv[2]);
/* socket: create the socket */
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
/* gethostbyname: get the server's DNS entry */
server = gethostbyname(hostname);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host as %s\n", hostname);
exit(0);
}
/* build the server's Internet address */
bzero((char *) &serveraddr, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serveraddr.sin_addr.s_addr, server->h_length);
serveraddr.sin_port = htons(portno);
/* connect: create a connection with the server */
if (connect(sockfd, &serveraddr, sizeof(serveraddr)) < 0)
error("ERROR connecting");
/* get message line from the user */
printf("Connection to server:port %s:%d\n",inet_ntoa(serveraddr.sin_addr),htons(portno));
printf("I never here here in presence of loop");
start = clock();
while(1){
/* send the message line to the server */
n = write(sockfd, buf, strlen(buf));
if (n < 0)
error("ERROR writing to socket");
/* print the server's reply */
n = read(sockfd, buf, BUFSIZE);
if (n < 0)
error("ERROR reading from socket");
printf("Echo from server: %s", buf);
}
printf("Time taken: %ld ",clock()-start);
close(sockfd);
return 0;
}
The line
printf("I never here here in presence of loop");
is not showing up because stdout is likely line-buffered and therefore output won't be visible until a newline is sent to stdout, or stdout is flushed.
If you change it to
printf("I never here here in presence of loop\n");
it will likely show up in your output.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm really confused. I have a C server and it was working great, but then I added some code, and I thought it was working fine until my c program randomly started changing the value of an int to a negative value.
Basically I'm having my server output the total bytes sent and midway through the transmission, always around 2100000000 bytes, the total bytes becomes negative. Here's an example of my output file. The value can't just become negative if you look at my code. So I suspect it's something weirder.
"345000","1470253912","59203","5592","2069901108"
"348000","1470253912","475539","4194","2092449162"
"351000","1470253912","830291","2796","2112043464"
"354000","1470253913","243217","1398","2133985176"
"357000","1470253913","708686","13980","-2135434834"
"360000","1470253914","173646","9786","-2109094024"
"363000","1470253914","514938","6990","-2089413400"
Anyways the thing I added, I commented it out, and I still came across the same error. Just for reference it's commented out in my code under tags "NEW STUFF ADDED". (I added it because of this post: Terminating C program on command line, but make sure writer is finished writing
)
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <signal.h>
#include <sys/time.h>
int PORT_NUM = 0;
int RecordRate = 3000;
FILE *fp;
typedef struct timeval timeval;
timeval time_;
void error(const char *msg)
{
perror(msg);
exit(1);
}
//NEW STUFF ADDED
//void sig_handler(int signo)
//{
// if (signo == SIGINT) {
// printf("received SIGINT\n");
// exit(0);
// fflush(fp);
// }
//}
int main(int argc, char *argv[])
{
int sockfd, newsockfd, portno;
socklen_t clilen;
char buffer[1000000];
struct sockaddr_in serv_addr, cli_addr;
int n;
PORT_NUM = atoi(argv[1]);
fp = fopen(argv[2],"w");
// NEW STUFF ADDED
// if (signal(SIGINT, sig_handler) == SIG_ERR)
// printf("\ncan't catch SIGINT\n");
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr));
//portno = atoi(argv[1]);
portno = PORT_NUM;
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr,
sizeof(serv_addr)) < 0)
error("ERROR on binding");
listen(sockfd,10);
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd,
(struct sockaddr *) &cli_addr,
&clilen);
if (newsockfd < 0)
error("ERROR on accept");
int counter = 0;
int total_bytes_sent = 0;
while(1){
bzero(buffer,1000000);
n = read(newsockfd,buffer,999999);
if (n < 0) {
error("ERROR reading from socket");
}
else if (n != 0) {
total_bytes_sent += n;
gettimeofday(&time_, NULL);
if(counter%RecordRate==0){
printf("counter %d \n", counter);
printf("Bytes Sent %d \n", total_bytes_sent);
fprintf(fp,"\"%d\",\"%ld\",\"%d\",\"%d\",\"%d\"\n", counter, time_.tv_sec, time_.tv_usec, n,total_bytes_sent);
}
counter++;
}
}
fclose(fp);
close(newsockfd);
close(sockfd);
return 0;
}
I swear I'm not trolling. I feared it was what I added that did this, but once I commented it out I got the same error. The thing is the error only became present after I added the code. So causation, correlation, no link?
How can this happen? And why always around 2100000000 bytes.
It's not the end of the world. I mean I can just hardcode something that makes sure the value is always, positive but I'm curious as to how this happens. Thanks.
Simply because ordinary signed int variables overflow at 231-1 (2147483647) and become negative.
Since this order of magnitude is not enough to keep track of the values you need, you should be using a 64bit variable to that - declare your variable as long long - and take proper care of this change in the places you are outputting this value to a text stream, and you should be good.
My code reads from a file line by line and sends it to a server.
client.c
int main(int argc, char *argv[])
{
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
FILE* pFile;
char* line = NULL;
//char buffer[256];
char* buffer;
int len;
if (argc < 3) {
fprintf(stderr,"usage %s hostname port\n", argv[0]);
exit(0);
}
pFile = fopen ("myfile.txt","r");
if (pFile==NULL)
{
printf("Error reading temp file\n");
exit (1);
}
portno = atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");
//loop
while (!feof(pFile)) {
//printf("Please enter the message: ");
line = readLine(pFile, line);
len=strlen(line);
buffer= (char*) malloc((len+1)*sizeof(char));
bzero(buffer,len);
memcpy(buffer,line,len+1);
// fgets(buffer,len,pFile);
printf("%s\n", buffer);
n = write(sockfd,buffer,strlen(buffer)+1);
if (n < 0)
error("ERROR writing to socket");
free(buffer);
free(line);
}
buffer= (char*) malloc(2048*sizeof(char));
bzero(buffer,2048);
n = read(sockfd,buffer,2048);
if (n < 0)
error("ERROR reading from socket");
printf("%s\n",buffer);
free(buffer);
fclose (pFile);
close(sockfd);
return 0;
}
And
/* A simple server in the internet domain using TCP
The port number is passed as an argument */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
void error(const char *msg)
{
perror(msg);
exit(1);
}
int main(int argc, char *argv[])
{
int sockfd, newsockfd, portno;
socklen_t clilen;
char buffer[2048];
struct sockaddr_in serv_addr, cli_addr;
int n;
if (argc < 2) {
fprintf(stderr,"ERROR, no port provided\n");
exit(1);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
else
printf("Socket connected\n");
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr,
sizeof(serv_addr)) < 0)
error("ERROR on binding");
listen(sockfd,5);
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd,
(struct sockaddr *) &cli_addr,
&clilen);
if (newsockfd < 0)
error("ERROR on accept");
printf("Data Receieved by client: \n");
bzero(buffer,2048);
n=read(newsockfd,buffer,2048);
if (n < 0) error("ERROR reading from socket");
printf("%s\n",buffer);
n = write(newsockfd,"Server received the message",18);
if (n < 0)
error("ERROR writing to socket");
close(newsockfd);
close(sockfd);
return 0;
}
The problem is that the server reveives a few lines and misses a few. Not able to figure out what is wrong. Can some one help?
Client Side
[gaurav1.k#DELL-BUILD03 Socket]$ gcc -Wall client.c -o client.exe
[gaurav1.k#DELL-BUILD03 Socket]$ ./client.exe localhost 8000
I am line number One,am I?
Here comes line number Two.
Will you welcome, Line number Three? And I am your Friend.
I am here, It is me - Line number Four.
Hello All, I am line number Five, am I? Yes I am.
It is over, because I am line number six.
Server received th
[gaurav1.k#DELL-BUILD03 Socket]$
Server Side:
[gaurav1.k#DELL-BUILD03 Socket]$ gcc -Wall server.c -o server.exe
[gaurav1.k#DELL-BUILD03 Socket]$ ./server.exe 8000
Socket connected
Data Receieved by client:
I am line number One,am I?
[gaurav1.k#DELL-BUILD03 Socket]$
The content of file to be read is:
I am line number One,am I?
Here comes line number Two.
Will you welcome, Line number Three? And I am your Friend.
I am here, It is me - Line number Four.
Hello All, I am line number Five, am I? Yes I am.
It is over, because I am line number six.
For a scenario like this you usually want to implement a kind of communication protocol.
Most importantly, the server needs to know how many bytes it has to read to receive the whole content. So usually, you transfer the message size as the first part of your message (header). Then the server knows how many bytes to receive after that to consume the actual payload data.
The problem is multiple write at the client side, but only one read at the server side. How?
For every line the client will write into the socket, that is multiple write(you are using write in a loop), but in server you are having one read, that is single read(no loop's, so it will read only the first line).
For first line, you are reading at server side. But for second line the client is writing, but your server have no read statement(first read is already executed). Due to this you wont receive the full message
A simple solution is write the whole file content at a time, not line by line and read it.
Try the below change also-
n = write(newsockfd,"Server received the message",50); // Increase the size
It looks like the problem is that you don't check the result of the read and write functions, which can fail in partial success states, indicating the number of bytes they've successfully transferred. In general, you need to wrap these functions in a loop that repeats until the entire buffer has been read/written.
On top of the failure to properly account for the returns from system calls, as described by other posters, there is:
bzero(buffer,2048);
n=read(newsockfd,buffer,2048)
..
printf("%s\n",buffer);
If the read() returns 2048 bytes, the printf can UB as it tries to find a non-existent null after the end of the buffer. Either allocate/clear 2049 of read 2047, and even that will only work well for transferring plain ASCII text files, (ie files with no embedded nulls).
Hello i am trying to make a TCP client/server that i want these things.
The client will give the filename or the path of filename of a file.
The server will find that file and give these details:
permissions,size,owner,group of owner,date modified/created,number of words,id and priority of user and send these to client of -1 if something goes wrong.The client will print that details.I have done a lot of this things but i have a huge problem so i cant continue,my problem is that server cant recognize path of file but i tried with naming the file and communication its OK.What i am doing wrong?
Thank you in advance
CLIENT
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
void error(char *msg)
{
perror(msg);
exit(0);
}
int main(int argc, char *argv[])
{
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[1024];
if (argc < 3) {
fprintf(stderr,"usage %s hostname port\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,&serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");
printf("Please enter the filename or path of filename: ");
bzero(buffer,1024);
fgets(buffer,1024,stdin);
n = write(sockfd,buffer,strlen(buffer));
if (n < 0)
error("ERROR writing to socket");
bzero(buffer,1024);
n = read(sockfd,buffer,1024);
if (n < 0)
error("ERROR reading from socket");
printf("%s\n",buffer);
return 0;
SERVER
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/resource.h>
#include <sys/time.h>
void error(char *msg)
{
perror(msg);
exit(1);
}
int main(int argc, char *argv[])
{
FILE *fp;
int sockfd, newsockfd, portno, clilen,i;
char buffer[1024],filename[1024];
char * pPath;
struct sockaddr_in serv_addr, cli_addr;
int n;
int which = PRIO_PROCESS;
id_t pid;
int ret;
if (argc < 2) {
fprintf(stderr,"ERROR, no port provided\n");
exit(1);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr,
sizeof(serv_addr)) < 0)
error("ERROR on binding");
listen(sockfd,5);
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd,
(struct sockaddr *) &cli_addr,
&clilen);
if (newsockfd < 0)
error("ERROR on accept");
bzero(buffer,1024);
n = read(newsockfd,buffer,1024);
if (n < 0) error("ERROR reading from socket");
printf("Here is the message: %s\n",buffer);
system("ls -al 1.txt > ls.txt");
system("wc -w 1.txt > wc.txt");
/* pPath = getenv ("PATH");
if (pPath!=NULL)
printf ("The current path is: %s\n",pPath);
system("touch path.txt");
fp=fopen("path.txt","w");
if (fp==NULL) exit(1);
fprintf(fp,pPath);
fclose(fp); */
pid = getpid();
ret = getpriority(which, pid);
printf("priority %d user id %d ret %d",which,pid,ret);
system("paste ls.txt wc.txt user.txt > info.txt");
fp=fopen("info.txt","r");
if (fp==NULL) exit(1);
for(int i=0;i<1000;i++){
fscanf(fp,"%c",&buffer[i]);
}
fclose(fp);
n = write(newsockfd,buffer,1024);
if (n < 0) error("ERROR writing to socket");
return 0;
}
}`
Thank you for the fast reply.To be specific,professor didn't ask us to make this txt files i created but i created cause i couldn't find a solution and i couldn't write everything to buffer.It should be like this:
buffer i coming with path from client
find path-file from buffer(this is where i have problem)
ls -al write to buffer(i wrote it to .txt)
wc write to buffer(i wrote it to .txt)
path write to buffer(haven't done this yet)
user info write to buffer(haven't done this yet)
buffer send to client
client prints buffer with all these info
I tried sprintf but i didn't understand exactly how you use it,but this commands looks better than mine thanks:).No is passed through buffer if i understand well.
You're probably going to need to pass the path into your system calls. Allocate a buffer (keep in mind that you should be doing checks on your buffers for security, but I understand this is probably homework) and use sprintf (http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/):
char lsbuf[1024];
sprintf(lsbuf,"ls -al %s > ls.txt",buffer);
system(lsbuf);
The proper way to do things (and the way your instructor most likely intends you to do them) would be to do the work of ls, wc, etc within the code. Calling system like this leaves you open to a whole new class of security holes.
Does the path passed to the server contain a trailing '\n'? If so you should remove it (for example by placing \0 character)
In your current code, nothing is really done with the input by the clients, and the behaviour does not match your description of it.
What is this supposed to do?:
for(int i=0;i<1000;i++){
fscanf(fp,"%c",&buffer[i]);
}
fclose(fp);
This will look for each character in the input (seeing as you use 1000 here, and the buffer can be 1024 characters, you are missing the last 24 characters) and return how many times it occurs in "info.txt". Note that you will also do a search for the NUL character ('\0'). Besides these carelessnesses it doesn't really do anything.
I assume you just want to find the string in the file, and work with the line number? You need a different method of searching strings. There are some clever and less clever algorithms for that. One of the more 'brute' algorithms is:
Search for the first character
Keep some flag as 'true' as long as all next characters match the expected character
If some character violates the match, go to the next search of the first character
Note that there are more efficient algorithms than this.
I did not scrutinize your network setup, assuming it works. It would be a good idea to either split the code up into several paragraphs using some more whitespace, or put the network setup into a different function.
First, use of bzero should be avoided since that function is deprecated. Use memset instead.
The function fgets, reads until a newline or the End-of-File is reached. Since a newline is a valid character, it is added to the string and a null character is appended.
If you type in "mytext" and then enter, the buffer will have "mytext\n\0".
Based on the current code, you are not even using the buffer from the client so it obvious it isn't working (not that it will due to the fgets() behavior due to an appended newline).
Sorry for replying like this but i didn't have an account,i am new to this(i didn't have problem with my projects for 4 years:P).I insert
char lsbuf[1024];
sprintf(lsbuf,"ls -al %s > ls.txt",buffer);
system(lsbuf);
and is working like a charm almost...It accepts the path and do ls but doesn't save the ls to ls.txt(creates empty file) and doesn't send it to buffer.Also i tried replaced memset and is working!!