473,396 Members | 2,020 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

What's wrong with this server code ?? Cant read incoming data

Hello,

I have been looking for some C-code which listens on a user-defined port
for incoming data traffic. When data is received, the data is written to a
file.

I found some C-code (server) that almost does the job. It listens on a
user-defined
port and responds to incoming data by writing how many times somebody
has tried to connect to the server.

I modified the code, but the read function returns an error (-1) and
incoming data
is not written to the buffer.

Anybody out there who can tell me what I am doing wrong?

Here is the code:

/* server.c - code for example server program that uses TCP */
#ifndef unix
#define WIN32
#include <windows.h>
#include <winsock.h>
#else
#define closesocket close
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#endif

#include <stdio.h>
#include <string.h>

#define PROTOPORT 5193 /* default protocol port number */
#define QLEN 6 /* size of request queue */

int visits = 0; /* counts client connections */
int nbytes;
/*------------------------------------------------------------------------
* Program: server
*
* Purpose: allocate a socket and then repeatedly execute the following:
* (1) wait for the next connection from a client
* (2) send a short message to the client
* (3) close the connection
* (4) go back to step (1)
*
* Syntax: server [ port ]
*
* port - protocol port number to use
*
* Note: The port argument is optional. If no port is specified,
* the server uses the default given by PROTOPORT.
*
*------------------------------------------------------------------------
*/
main(argc, argv)
int argc;
char *argv[];
{
struct hostent *ptrh; /* pointer to a host table entry */
struct protoent *ptrp; /* pointer to a protocol table entry */
struct sockaddr_in sad; /* structure to hold server's address */
struct sockaddr_in cad; /* structure to hold client's address */
int sd, sd2; /* socket descriptors */
int port; /* protocol port number */
int alen; /* length of address */
char buf[1000]; /* buffer for string the server sends */

#ifdef WIN32
WSADATA wsaData;
WSAStartup(0x0101, &wsaData);
#endif
memset((char *)&sad,0,sizeof(sad)); /* clear sockaddr structure */
sad.sin_family = AF_INET; /* set family to Internet */
sad.sin_addr.s_addr = INADDR_ANY; /* set the local IP address */

/* Check command-line argument for protocol port and extract */
/* port number if one is specified. Otherwise, use the default */
/* port value given by constant PROTOPORT */

if (argc 1) { /* if argument specified */
port = atoi(argv[1]); /* convert argument to binary */
} else {
port = PROTOPORT; /* use default port number */
}
if (port 0) /* test for illegal value */
sad.sin_port = htons((u_short)port);
else { /* print error message and exit */
fprintf(stderr,"bad port number %s\n",argv[1]);
exit(1);
}

/* Map TCP transport protocol name to protocol number */

if ( ((int)(ptrp = getprotobyname("tcp"))) == 0) {
fprintf(stderr, "cannot map \"tcp\" to protocol number");
exit(1);
}

/* Create a socket */

sd = socket(PF_INET, SOCK_STREAM, ptrp->p_proto);
if (sd < 0) {
fprintf(stderr, "socket creation failed\n");
exit(1);
}

/* Bind a local address to the socket */

if (bind(sd, (struct sockaddr *)&sad, sizeof(sad)) < 0) {
fprintf(stderr,"bind failed\n");
exit(1);
}

/* Specify size of request queue */

if (listen(sd, QLEN) < 0) {
fprintf(stderr,"listen failed\n");
exit(1);
}

/* Main server loop - accept and handle requests */

while (1) {
alen = sizeof(cad);
if ( (sd2=accept(sd, (struct sockaddr *)&cad, &alen)) < 0) {
fprintf(stderr, "accept failed\n");
exit(1);
}
visits++;
//sprintf(buf,"This server has been contacted %d
time%s\n",visits,visits==1?".":"s.");
//send(sd2,buf,strlen(buf),0);

// read returns an error (-1)
nbytes=read(sd2,buf,strlen(buf));
printf("read %d bytes of data",nbytes);
closesocket(sd2);
}
}



Jan 23 '07 #1
5 2596
Jens wrote:
Hello,

I have been looking for some C-code which listens on a user-defined port
for incoming data traffic. When data is received, the data is written to a
file.
While sockets are OT here, one obvious error isn't:
char buf[1000]; /* buffer for string the server sends */
Note the array buf isn't initialised.
nbytes=read(sd2,buf,strlen(buf));
You are calling strlen on an initialised buffer.

Use a constant for the size.

--
Ian Collins.
Jan 23 '07 #2
Ian Collins wrote:
Jens wrote:
>>Hello,

I have been looking for some C-code which listens on a user-defined port
for incoming data traffic. When data is received, the data is written to a
file.

While sockets are OT here, one obvious error isn't:

> char buf[1000]; /* buffer for string the server sends */

Note the array buf isn't initialised.

>>nbytes=read(sd2,buf,strlen(buf));


You are calling strlen on an initialised buffer.

Use a constant for the size.
Or sizeof(buf).

--
Ian Collins.
Jan 23 '07 #3
"Jens" <je**@jensen.notwrites:
I have been looking for some C-code which listens on a user-defined port
for incoming data traffic. When data is received, the data is written to a
file.
[snip]

You also posted this in comp.std.c. It's off-topic in both
newsgroups. See my respones there.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jan 23 '07 #4
Flash Gordon <sp**@flash-gordon.me.ukwrites:
Jens wrote, On 23/01/07 21:56:
[...]
if (port 0) /* test for illegal value */

What about a number above 63353? (he says making use of off topic knowledge)
Do you mean 65535 (2**16-1)?

[...]
exit(1);

Non-portable return value. Include stdlib.h at the top then use
exit(EXIT_FAILURE);
Non-portable return values are not unreasonable in non-portable code.
Judging by the non-standard (or other-standard) library routines being
used, it's likely that "exit(1)" is a correct way to indicate an
error.

On the other hand, using "exit(EXIT_FAILURE)" on such systems is
likely to yield identical results.

If the program defines (and documents!) multiple failure codes, and 1
is just one among several such codes, then using exit(1) is reasonable
(though defining and using constants would be better). If you're
just signally generic failure, exit(EXIT_FAILURE) is probably
preferred.

[...]

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jan 24 '07 #5
Keith Thompson wrote, On 24/01/07 00:17:
Flash Gordon <sp**@flash-gordon.me.ukwrites:
>Jens wrote, On 23/01/07 21:56:
[...]
>> if (port 0) /* test for illegal value */
What about a number above 63353? (he says making use of off topic knowledge)

Do you mean 65535 (2**16-1)?
Yes. Just a tripeographical error. Although I can't see how I managed it!
[...]
>> exit(1);
Non-portable return value. Include stdlib.h at the top then use
exit(EXIT_FAILURE);

Non-portable return values are not unreasonable in non-portable code.
Judging by the non-standard (or other-standard) library routines being
used, it's likely that "exit(1)" is a correct way to indicate an
error.

On the other hand, using "exit(EXIT_FAILURE)" on such systems is
likely to yield identical results.

If the program defines (and documents!) multiple failure codes, and 1
is just one among several such codes, then using exit(1) is reasonable
(though defining and using constants would be better). If you're
just signally generic failure, exit(EXIT_FAILURE) is probably
preferred.
The only failure code used was 1. Had there been different codes for
different failures then, as you say, it would have been more reasonable.

So I basically agree with all your comments.
--
Flash Gordon
Jan 24 '07 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

125
by: Sarah Tanembaum | last post by:
Beside its an opensource and supported by community, what's the fundamental differences between PostgreSQL and those high-price commercial database (and some are bloated such as Oracle) from...
1
by: Miller | last post by:
Hi everybody! These messages have been found in the System log of the Event Viewer application. These error messages have been generated after each logon attempt. Although dial-in client have been...
47
by: ship | last post by:
Hi We need some advice: We are thinking of upgrading our Access database from Access 2000 to Access 2004. How stable is MS Office 2003? (particularly Access 2003). We are just a small...
3
by: Brian Birtle | last post by:
**** A CHALLENGE TO THE GURUS - refute the statement "It's impossible to build a file upload progress meter using ASP.NET" **** First person to prove me wrong gets "All Time .NET Programming GOD"...
8
by: Midnight Java Junkie | last post by:
Dear Colleagues: I feel that the dumbest questions are those that are never asked. I have been given the opportunity to get into .NET. Our organization has a subscription with Microsoft that...
6
by: mike | last post by:
Failed to update database "D:\INETPUB\WWWROOT\ADROUTER\APP_DATA\ADROUTER.MDF" because the database is read-only. Description: An unhandled exception occurred during the execution of the current...
0
by: craze3 | last post by:
I have programmed an XML Socket Server to communicate with Flash. It doesn't print out the messages it has received from the flash until the server has been shut down. Any ideas? The part with...
167
by: darren | last post by:
Hi I have to write a multi-threaded program. I decided to take an OO approach to it. I had the idea to wrap up all of the thread functions in a mix-in class called Threadable. Then when an...
1
by: DarkGiank | last post by:
Hi, im new to csharp and im trying to create a class that can change the application database without no rewriting all connection code... but cause some reason it is not working... it tells me that...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.