Right now, I'm trying to write a simple client/server application in order to measure the round trip time on a LAN for TCP messages of various sizes (I'm doing the timing client side). The program works fine for small packet sizes (> 1000 bytes) but I end up with a segmentation fault: 11 error for inputs of larger magnitude (10KB or greater).
int main()
{
struct sockaddr_in sin;
char buf[MAX_LINE];
int len;
int s, new_s;
/* build address data structure */
bzero((char *)& sin, sizeof( sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = INADDR_ANY;
sin.sin_port = htons( SERVER_PORT);
/* setup passive open */
if (( s = socket( PF_INET, SOCK_STREAM, 0)) < 0) {
perror("tcp program: socket");
exit(1);
}
if (( bind(s, (struct sockaddr *)& sin, sizeof(sin))) < 0) {
perror("tcp program: bind");
exit( 1);
}
listen(s, MAX_PENDING);
/* wait for connection, then receive and print text */
while(1) {
socklen_t lent = (unsigned int)&len;
if ((new_s = accept(s, (struct sockaddr *)& sin, &lent)) < 0) {
perror("tcp program: accept");
exit( 1);
}
while ((len = recv(new_s, buf, sizeof(buf), 0))){
char msg[len];
send( new_s, msg, len, 0); //echo message of same length as received message
}
close(new_s);
}
}
Again, the goal was to measure RTT, so I wanted the client to send a message, the above server to receive it, then send back a message of equivalent size. I also wanted the server to continue spinning so that the client could run iteratively, sending messages of 1KB, 10KB,...1000KB, etc. However, such iterations usually result in a segmentation fault.
Oddly enough, if I configure my client to run, for example, a single 12KB message send, the server does fine, and continues to run. And if I wait a couple of seconds, I can even repeatedly call my client and the server keeps up. But if I run the single message send in rapid succession, I end up with the segfault again.
Any ideas? I apologize in advance for any elementary errors in style or format. This is my first real foray into the C language beyond "hello world".
Thanks!