C's printf and fprintf(stdout,) are not printing - c

This is a bit of an odd one. My code wasn't outputting what I thought it should. I added some print statements at various stages to see where it was going wrong. Still nothing.
So I added a printf statement at the start of main. That's where I got really confused.
So I presumed something funny was happening with the file descriptors. I changed the printf to a fprintf. Still nothing. Printing to stderr with fprintf does work! Why is this happening?
Removing all of the body from main except the initial print statement and the return does print.
Code
int main(void) {
fprintf(stdout, "STARTED!");
//Create an Internet domain socket
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
//If this fails exit and print the error
if (sockfd == -1) {
printf("Error %d, cannot create socket", errno);
return 1;
}
printf("SOCKET CREATED!");
//Creates a socket address
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(8080);
addr.sin_addr.s_addr = INADDR_ANY;
//Attempts to bind to the socket address, again prints to error if this fails.
if (bind(sockfd, (struct sockaddr *) &addr, sizeof(addr)) == -1)
{
printf("Error %d, cannot bind", errno);
return 1;
}
//Starts Listening for a client
if (listen(sockfd, 1) == -1)
{
printf("Error %d, cannot listen", errno);
return 1;
}
//If all is successful, server is operational
while(1)
{
//Creates a file descripter for the connection
int connfd;
//And a socket address for the client
struct sockaddr_in cliaddr;
socklen_t cliaddrlen = sizeof(cliaddr);
//If a connection attempt is made accepts it.
connfd = accept(sockfd, (struct sockaddr *) &cliaddr, &cliaddrlen);
if (connfd == -1) {
//If the connection fails print an error
printf("Error %d, cannot accept connection", errno);
continue;
}
//Otherwise process the request
else {
printf("CONNECTED!");
char end;
end = 1;
while (end)
{
process_request(connfd);
end = 0;
}
}
close(connfd);
}
close(sockfd);
return 0;
}

Output is often buffered by the system. You can call fflush, but sometimes, depending on how the caching works, simply ending the output with a newline is sufficient. So try changing
fprintf(stdout, "STARTED!");
to
fprintf(stdout, "STARTED!\n");
And, if that doesn't help, to
fprintf(stdout, "STARTED!\n");
fflush(stdout)
(And stderr often isn't cached, as you want to see errors immediately.)
Finally, you will see output when the program finishes (as things are flushed then), which probably explains the rest of the behaviour.

Related

Client only receiving partial data back from the server via a socket in C

Brand new to StackOverflow and definitely brand new to figuring out how to get sockets to work in C. Here's what I'm trying to do: I need to create two programs where one acts as a "daemon" (not actually, you just launch it first and it runs in the background) that listens on a specified port, and then another program that attempts to send information -- via that port -- from a plaintext file, along with the name of a "key" file that should be used to encrypt it. The daemon program connects to the (let's call it client) program, forks off a new process, accepts the information, encrypts the text accordingly, and then sends it back to the client program to be stored in a file.
This last part is where I'm having trouble. I've been able to successfully transfer all of the data from the client to the daemon program, and even successfully encrypt it; I tried storing the info into a temp file to see how it was coming out and everything looked as it should. But when I try to send the information back -- it's worth noting that I'm trying to send it back in chunks as the daemon program is encrypting it and therefore potentially still receiving info -- the client only receives a fraction of the data before the connection is seemingly closed and the process is finished.
Sorry for the lengthy post, just trying to be as detailed as possible. I tried searching for some posts regarding this topic and I did find this one, but it wasn't quite the same issue (plus the suggested fixes were things I already tried). Below is what I think is the pertinent code. This is only my current set up, so certain aspects might just be random bits from different approaches I've tried, e.g. the shutdown on write on the client side is a recent addition that doesn't appear to have made a difference. I've tried a number of different things to make this work over the past week, so if any of the suggestions that come in are things that I've tried, I'll let you folks know. Thanks in advance!
Client:
//Create socket, check for success
//
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd == -1){
fprintf(stderr, "socket creation failed");
exit(1);
}
//Create address structure for socket to connect to
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_port = htons(port);
server.sin_addr.s_addr = INADDR_ANY;
int success;
success = connect(sockfd, (struct sockaddr*) &server, sizeof(server));
if(success == -1){
fprintf(stderr, "Could not find port, failed to connect socket\n");
exit(2);
}
//IF all is well, open up the plaintext file for extracting data
FILE* ptextSend = fopen(argv[1], "r");
int totalNeeded;
rewind(ptextSend);
fseek(ptextSend, 0L, SEEK_END);
totalNeeded = ftell(ptextSend);
totalNeeded = totalNeeded - 1;
rewind(ptextSend);
//First, send key path
send(sockfd, keypath, sizeof(keypath), 0);
//Then, send contents of file
int n = 0;
char buffer[1000];
while(n < totalNeeded){
fgets(buffer, 1000, ptextSend);
printf("right now buffer is %s\n", buffer);
n = n + (send(sockfd, buffer, sizeof(buffer), 0));
}
shutdown(sockfd, 1);
//Attempt to receive encrypted info back
n=1;
while(n != 0){
char* newBuff[1000];
n = recv(sockfd, newBuff, sizeof(newBuff) - 1, 0);
if(n!=0)
fprintf(stdout, "this is the client: %s\n", newBuff);
}
Daemon/Server code:
//Create socket
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd == -1){
fprintf(stderr, "Server error: failure to create socket.\n");
exit(1);
}
//Create address for socket
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_port = htons(port);
server.sin_addr.s_addr = INADDR_ANY;
//Bind socket to port using address struct
int bindSuccess = bind(sockfd, (struct sockaddr*) &server, sizeof(server));
if(bindSuccess == -1){
fprintf(stderr, "Server error: bind call failed.\n");
exit(1);
}
//Set socket to listen
int listenSuccess = listen(sockfd, 5);
if(listenSuccess == -1){
fprintf(stderr, "Server error: listen call failed.\n");
exit(1);
}
//Accept next client connection
struct sockaddr_in client_addr;
socklen_t client_length = sizeof(client_addr);
int client_sockfd = accept(sockfd, (struct sockaddr*) &client_addr, &client_length);
if(client_sockfd == -1){
fprintf(stderr, "Server error: accept call failed.\n");
exit(1);
}
pid_t pid = fork();
if(pid < 0){
fprintf(stderr, "Error forking process on connection.\n");
exit(1);
}
if(pid == 0){
//First receive key path
char keybuff[100];
recv(client_sockfd, keybuff, sizeof(keybuff),0);
FILE* theKey = fopen(keybuff, "r");
char buffer[1000];
int n = 1;
while(n != 0){
n = recv(client_sockfd, buffer, sizeof(buffer) - 1, 0);
strtok(buffer, "\n");
char* newString = encrypt(buffer, theKey);
send(client_sockfd, newString, sizeof(newString) - 1, 0);
}
if(n == -1){
fprintf(stderr, "Server error: failed to read from socket.\n");
exit(1);
}
fclose(theKey);
close(client_sockfd);
close(sockfd);
return 0;
}else
return 0;
}
What I should be getting back is "right now buffer is: THE RED GOOSE FLIES AT MIDNIGHT STOP" followed by its encrypted version, so 36 characters of gibberish (occasionally broken up with "this is the client" and a newline). Instead, the total output is:
right now buffer is THE RED GOOSE FLIES AT MIDNIGHT STOP
this is the client: BPZDOSZ
...so just seven characters worth of data and then it exits (successfully).

Why won't my server implementation run concurrently properly?

I am attempting to create a client/server system that can handle multiple concurrent connections using the unix system call fork.
The client enters a movie title, and the server will check if the movie was there or not. If it was there, it would tell the client the ranking, the name, and the box records.
looking at my forking implementation, the client asks for user input, however the program just simply goes pass it.
OUTPUT EXAMPLE:
connection made with client 127.0.0.1
PID IS 27270
--> all messages read - connection being closed
CLIENT: Please input an string: PID IS 0
At this line, CLIENT: Please input an string: PID IS 0, the user was suppose to input a string, however the program glances over it. How do I make the program take in the string from the client?
SERVER CODE:
int main()
{
int sock, clientsock, mlen, addrsize, msgct, chc, chct, pid;
struct sockaddr_in addr; //ipv4 address
char ch, buf[80];
/*
* Create a socket.
*/
sock = socket(AF_INET, SOCK_STREAM,0); //create socket (AF_NET shows its ipv4 internet connection, SOCK_STREAM shows its a tcp)
if (sock == -1)
{
perror("opening socket");
exit(-1);
}
//Bind socket to local address
/*
* Bind a name to the socket. Since the server will bind with
* any client, the machine address is zero or INADDR_ANY. The port
* has to be the same as the client uses.
*/
addr.sin_family = AF_INET;
addr.sin_port = htons (32351); //port number for local address
addr.sin_addr.s_addr = htonl (INADDR_ANY); //ip address (you can also hard code it)
if (bind(sock, (struct sockaddr *) &addr, //binding, first parameter : is the socket you created, &addr is the
sizeof (struct sockaddr_in)) == -1) //error checking
{
perror ("on bind");
exit (-1);
} //(at this moment we have binded socket)
/*
* Make the socket available for potential clients.
*/
//if there is connection or not?
if (listen(sock,1) == -1)
{
perror("on listen");
exit(-1);
}
//-------Text File Implementation-----------
FILE *fp;
char data[5][200];
char rank[5][2];
char name[5][255];
char value[5][100];
/* opening file for reading */
fp = fopen("movie.txt", "r");
if(fp == NULL) {
perror("Error opening file");
return(-1);
}
fgets (data[0], 200, fp);
int i = 1;
while(fgets (data[i], 200, fp)!=NULL)
{
/* writing content to stdout */
sscanf(data[i],"%s %[^$] %s",rank[i],name[i],value[i]);
puts(data[i]);
i+=1;
}
//CODE DOES NOT IMPLEMENT AFTER THIS WHILE LOOP
//close the file
fclose(fp);
addrsize = sizeof(struct sockaddr_in);
//THIS WHILE LOOP IS NOT BEING IMPLEMENTED...
while(1)
{
clientsock = accept(sock, (struct sockaddr *) &addr, &addrsize);
if (clientsock == -1)//error checking
{
perror("on accept");
exit(-1);
}
printf("connection made with client ");
printf ("%s\n", inet_ntoa (addr.sin_addr)); //also print client address
/* Create child process */
pid = fork();
if (pid < 0)
{
perror("ERROR on fork");
exit(1);
}
if (pid == 0)
{
/* This is the client process */
close(sock);
bool exist = false;
mlen = recv (clientsock, buf, 80, 0);
if (mlen < 0)
{
perror("ERROR reading from socket");
exit(1);
}
int lenS;
int which;
for(int i = 1; i<5; i++)
{
printf("%s\n\n", name[i]);
char *pch = strstr(name[i],buf);
if(pch != NULL)
{
which = i;
exist = true;
puts("GOOD");
}
else
{
puts("bad");
}
}
if(exist)
{
//SEND TO CLIENT FROM HERE!
printf("%s\n", rank[which]);
printf("%s\n", name[which]);
printf("%s\n", value[which]);
lenS = strlen(name[which]);
send (clientsock, name[which], lenS+1, 0);
}
else
{
//SEND TO CLIENT FROM HERE!!!!
printf("NOT HERE ");
send (clientsock, "NOT HERE", 9, 0);
}
printf("Here is the message: %s\n",buf);
exit(0);
}
else
{
close(clientsock);
printf(" --> all messages read - connection being closed\n");
}
}
}
CLIENT CODE:
int main()
{
int sock, addrsize;
struct sockaddr_in addr;
unsigned int in_address;
char buf[80];
int mlen;
/*
* Open a socket for Internet stream services.
*/
sock = socket(AF_INET, SOCK_STREAM,0); //creating a socket to connect to server, AF_INET : ipv4 internet connection, SOCK_STREAM tcp
if (sock == -1)
{ perror("opening socket");
exit(-1);
}
addr.sin_family = AF_INET;
addr.sin_port = htons (32351); //port number has to be the same as the one from server
in_address = 127 << 24 | 0 << 16 | 0 << 8 | 1; //ip address, local host, since we are running client and server on the same computer, it needs to have the same ip address
addr.sin_addr.s_addr = htonl (in_address);
if (connect (sock, (struct sockaddr *) &addr, //binding
sizeof (struct sockaddr_in)) == -1)
{
perror("on connect");
exit(-1);
}
char word[100];
int len;
printf("CLIENT: Please input an string: ");
scanf("%s", word);
//printf("You entered: %s\n", word);
len = strlen(word);
send (sock, word, len+1, 0);
mlen = recv (sock, buf, 80, 0);
printf ("%s\n\n\n\n\n\n\n", buf);
/*
* Do a shutdown to gracefully terminate by saying - "no more data"
* and then close the socket -- the shutdown is optional in a one way
* communication that is going to terminate, but a good habit to get
* into.
*/
if (shutdown(sock, 1) == -1)
{
perror("on shutdown");
exit(-1);
}
printf ("Client is done\n");
close(sock);
}
You are running the client and server programs on the same machine, with the same controlling terminal. The server master process, its client-service subprocess(es), and the independent client process therefore may all write to that terminal. They run independently and concurrently, so their outputs can be mashed up.
The fact that the PID IS 0 message is emitted after the prompt does not indicate that the client program has skipped accepting input, which indeed, I don't see how it could do. The prompt and the PID message come from different processes.
It would make things clearer to launch the server process and the client process from separate (virtual) terminals, so that their output is not mixed.

C Sock-Programming Problems with accept

Im programming a server/client program and have a weird problem here....
The server binds a socket and listening to a socket. But it is stucked at accepting the client. It is a simulation of a bank program. The server stores a balance of one account and do what the client wants. The weird situation is that I've got no error messages at accepting and the server prints my message on the console "Accepted", but it did not do the next print message. But the writing of the balance to the client did well because the client gets the right value.....the next print message is also ignored by the server.....whats wrong here??? The program is not ready yet and i'm only testing a few functionalities here.
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <netdb.h>
#include <arpa/inet.h>
#define MAX 20
int main(int argc, char **argv){
int sockfd,csocket;
struct sockaddr_in addr,client_addr;
socklen_t clilen;
clilen = sizeof(client_addr);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
fprintf(stderr, "Error in opening socket - %s\n", strerror(errno));
return EXIT_FAILURE;
}
addr.sin_family = AF_INET;
addr.sin_port = htons(atoi(argv[1]));
addr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(sockfd, (struct sockaddr *) &addr, sizeof(struct sockaddr_in)) < 0){
fprintf(stderr, "Error in binding - %s\n", strerror(errno));
return EXIT_FAILURE;
}
printf("Bind\n");
int list = listen(sockfd, SOMAXCONN);
if (list < 0) {
fprintf(stderr, "Error in listening - %s\n", strerror(errno));
return EXIT_FAILURE;
}
printf("Listening\n");
char sel;
int tmp,bal=666;
while(1) {
//newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
csocket = accept(sockfd,(struct sockaddr *) &client_addr,&clilen);
if (csocket < 0) {
fprintf(stderr, "Error in accepting - %s\n", strerror(errno));
return EXIT_FAILURE;
}
printf("Accepted\n");
printf("Writing balance");
if (write(csocket,&bal,sizeof(int))<0){
fprintf(stderr, "Error in Writing - %s", strerror(errno));
return EXIT_FAILURE;
}
printf("Writing balance");
if(read(csocket, &sel, sizeof(char))<0){
fprintf(stderr, "Error in reading - %s\n", strerror(errno));
return EXIT_FAILURE;
}
printf("User wählt:%c\n",sel);
/********Einzahlen**********/
if (sel=='e'){
printf("Neuer Kontostand: %d", bal);
if(read(csocket, &tmp, sizeof(int))<0){
fprintf(stderr, "Error in accepting - %s\n", strerror(errno));
return EXIT_FAILURE;
}
bal+=tmp;
printf("Neuer Kontostand: %d", bal);
}
if(sel=='q'){
close(csocket);
printf("User beendet\n");
}
}
}
The Client
{add include part here}
int main(){
int sockfd;
socklen_t addrlen;
addrlen = sizeof(struct sockaddr_in);
struct sockaddr_in addr;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
char ip[16];
printf("IP (Press 0 for 127.0.0.1):");
scanf("%15s", ip);
//printf("\n");
if (ip[0]=='0'){
strcpy(ip,DEFAULT_IP);
printf("Setting IP to 127.0.0.1\n");
}
printf("%s",ip);
int port;
printf("Port:");
scanf("%d",&port);
printf("\n");
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr=inet_addr(ip);
int tmp;
if (connect(sockfd, (struct sockaddr *) &addr, sizeof(struct sockaddr_in))<0){
fprintf(stderr, "Error in connecting - %s\n", strerror(errno));
}
printf("Connected\n");
int bal,w;
if(read(sockfd, &bal, sizeof(int))<0){
fprintf(stderr, "Error in accepting - %s\n", strerror(errno));
return EXIT_FAILURE;
}
printf("Balance:%d\n",bal);
printf("Geld [e]inzahlen\n"); //add money to account
printf("Geld [a]uszahlen\n"); //Getting money from account
char msg[MAX];
printf("Enter your choce:\n");
scanf("%s",msg);
if (msg[0]=='e'){
printf("How much?:\n");
scanf("%i",&w);
if (write(sockfd,&w,sizeof(int))<0 ){
fprintf(stderr, "Error in Writing - %s", strerror(errno));
return EXIT_FAILURE;
}
bal+=w;
}
printf("sended");
if (close(sockfd) < 0) {
fprintf(stderr, "Error in closing socket - %s\n", strerror(errno));
}
}
The immediate problem is combination of two things.
First, you print "Accepted" without newline. Standard output is line buffered, so it will not be printed until you print a newline (or read input from stdin, or explicit fflush(stdout);).
Second, you then enter read, which apparently never returns. Theoretically, also the write could block, but you say client receives the write, so server must be stuck at the read.
End result, your server program is indefinitely stuck at the read. And the output you thought you printed is stuck at the stdout buffers, waiting to be flushed.
The reason for this is simple: your client writes only 4 bytes, but your server tries to read 4+1 bytes. So actually it is the 2nd read at server, which blocks indefinitely.
Some general hints:
At Stack Overflow, please look at the preview and make sure your code is properly indented, or fewer people will bother to even look at it (hint: avoid TABs, use only spaces to indent, to avoid extra hassle).
Always check return value of any scanf functions, and doubly so if you are reading user input from keyboard. Even if it is just experimental code, you don't want to waste time solving bugs which are not bugs but normal behaviour of scanf.
When copy-pasting, try to fix the strings you copy paste, such as function names in your error messages, or you will be confused by "wrong" error message texts of your own.
You need a call to the select() function to test if the file descriptor is ready prior to the accept(). Also look up fd_set and the related FD_ZERO, FD_SET, and FD_ISSET macros. They are needed to monitor whether the socket is ready to accept the incoming connection. This is a great resource for socket programming.

return from read in connected udp sockets in c

i programming UDP client/Server model and the main functionaly for this app is client insert the directory path then the server will retrun the contents of supplied directory to the client, so this Client code :
#include "cliHeader_UDP.h"
int
main(int argc, char **argv)
{
int sockfd;
struct sockaddr_in servaddr;
/*Error checking for providing appropirate port# */
if(argc<3 )
err_quit("Error,no port provided, please enter the port#:22011 \n");
portno=atoi(argv[2]);
for(;;)
{
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(portno);
Inet_pton(AF_INET, argv[1], &servaddr.sin_addr);
sockfd = Socket(AF_INET, SOCK_DGRAM, 0);
dg_cli(stdin, sockfd, (SA *) &servaddr, sizeof(servaddr));
}
exit(0);
}
**//and here is the dg_cli implemntation :**
void
dg_cli(FILE *fp, int sockfd, const SA *pservaddr, socklen_t servlen)
{
int n;
char sendline[MAXLINE], recvline[MAXLINE + 1];
Connect(sockfd, (SA *) pservaddr, servlen);
for(;;)
{
bzero(&sendline, sizeof(sendline));
printf("please enter Directory Name :\n");
Fgets(sendline, MAXLINE, fp);
/*To check if the supplied name ended with \n in sendline buffer */
if((p = strchr(sendline, '\n'))) *p = 0;
write(sockfd, sendline, strlen(sendline));
printf("test for write\n");
**Line 31.......:** while ( (n=read(sockfd, recvline, MAXLINE)) )
{
if(n<0)
perror("Error");
printf("recvline is: %s\n",recvline);
printf("n========%d\n",n);
}
printf("exit from read While\n");
recvline[n] = 0; /* null terminate */
}
}
the problem in Line 31... is the 1st time run as i wanted client insert DIR path so the server will return the contents of the path ,but when the user need to insert again the path ,its still blocking in read in the for loop and does not return from for loop ,
so how to put condtion when the contents of buffer ended return from for loop like EOF in TCP
As you noticed there's no concept of "connection" in UDP - even if you called connect(2) - so there's no way for read to return 0 when the communication is over. There are ways to fix this:
Have the server send a 0-length message when the output is over or some other special marker
Have the client analyze the input and somehow detect it is over
Both these methods are a little bit fragile in practice: imagine what happens if the "output is over" message gets lots. So you'll also have to provision for that case and maybe add a timeout (look for SO_RCVTIMEO for example).
i tried some thing like that have a look :
part of code at server side:
//at server side Read the directory contents
printf("The contents of [%s] is :\n",mesg);
bzero(&mesg, sizeof(mesg));
while( (dptr = readdir(dp)) !=NULL )
{
printf(" \n[%s] \t",dptr->d_name);
//report(dptr->d_name, &status_buf);
sprintf(mesg,"%s",dptr->d_name);
if((dptr = readdir(dp)) ==NULL)
{
bzero(&mesg, sizeof(mesg));
sprintf(mesg,"%c",'!');
Sendto(sockfd, mesg, sizeof(mesg), 0, pcliaddr, len);
}
Sendto(sockfd, mesg, sizeof(mesg), 0, pcliaddr, len);
}
// Close the directory stream
closedir(dp);
//and at the client side :
flag=1;
while ( (n=read(sockfd, recvline, MAXLINE)) )
{
if(n<0)
perror("Error");
printf("recvline is: %s\n",recvline);
flag=flag+1;
printf("Flag now is :%d\n",flag);
printf("n========%d\n",n);
bzero(&recvline, sizeof(recvline));
if(recvline[0]=='!')
return;
}

maximum data that can be sent through a port-socket

i have implemented a program which takes input from client, performs operation on server and writes the data to the client. ls command is what i have chosen for example.
Now my doubt is,
1) what if the input is very huge in bytes??
2) what is the maximum data that can be sent through a socket port??
client.c
int main()
{
FILE *fp;
int servfd, clifd;
struct sockaddr_in servaddr;
struct sockaddr_in cliaddr;
int cliaddr_len;
char str[4096], clientip[16];
int n;
servfd = socket(AF_INET, SOCK_STREAM, 0);
if(servfd < 0)
{
perror("socket");
exit(5);
}
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(SERVPORT);
servaddr.sin_addr.s_addr = inet_addr(SERVIP);
if(bind(servfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0)
{
perror("bind");
exit(0);
}
listen(servfd, 5);
printf("Server is waiting for client connection.....\n");
while(1)
{
cliaddr_len=sizeof(cliaddr);
clifd = accept(servfd, (struct sockaddr *)&cliaddr, &cliaddr_len);
strcpy(clientip, inet_ntoa(cliaddr.sin_addr));
printf("Client connected: %s\n", clientip);
if(fork() == 0)
{
close(servfd);
while(1)
{
n = read(clifd, str, sizeof(str));
str[n] = 0;
if(strcmp(str, "end") == 0)
{
printf("\nclient(%s) is ending session and server is waiting for new connections\n\n", clientip);
break;
}
else if (strcmp(str, "ls") == 0) {
system("ls >> temp.txt");
fp = fopen("temp.txt", "r");
fread(str, 1, 500, fp);
remove("temp.txt");
}
else
printf("Received from client(%s): %s\n", clientip, str);
write(clifd, str, strlen(str));
}
close(clifd);
exit(0);
}
else
{
close(clifd);
}
}
}
server.c
int main()
{
int sockfd;
struct sockaddr_in servaddr;
char str[500];
int n;
sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(SERVPORT);
servaddr.sin_addr.s_addr = inet_addr(SERVIP);
if(connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0)
{
printf("Could not connect to server: %s\n", strerror(errno));
exit(1);
}
while(1)
{
printf("Enter message: ");
scanf(" %[^\n]", str);
write(sockfd, str, strlen(str));
if(strcmp(str, "end") == 0)
break;
n = read(sockfd, str, sizeof(str));
str[n] = 0;
printf("Read from server: %s\n", str);
}
close(sockfd);
}
As for your question no 1. the huge data is broken in many packets & then sent packet by packet its done by OS internally. & the one packet size depends on your system OS(you can change it.It is called MTU maximum transfer unit).
& for your question no 2. the data send by a socket port may be infinite coz as long as u wish to send data it will send. there is no limit.!!!
Q: What if the input is very huge in bytes?? What is the maximum data that can be sent through a socket port??
A: There is no limit on the size of a TCP/IP stream. In theory, you could send and receive an infinite number of bytes.
... HOWEVER ...
1) The receiver must never assume is will ever get all the bytes at once, in a single read. You must always read socket data in a loop, reading as much at a time as you wish, and appending it to the data you've already read.
2) You can send a "large" amount of data at once, but the OS will buffer it behind your back.
3) Even then, there's an OS limit. For example, here the maximum send buffer size is 1 048 576 bytes.:
http://publib.boulder.ibm.com/infocenter/tpfhelp/current/index.jsp?topic=%2Fcom.ibm.ztpf-ztpfdf.doc_put.cur%2Fgtpc2%2Fcpp_send.html
If you need to send more, you must send() in a loop.
PS:
As Anish recommended, definitely check out Beej's Guide to Network programming:
http://beej.us/guide/bgnet/output/html/multipage/

Resources