2

Ive written the following echo server using UDP but i have no idea that why it is giving me Segmentation Fault in sendto function, it receives fine but has problem sending data back to client. Ive been trying to find the problem for a few hours now but got no where. Can somebody please point out the fault or what i may be doing wrong. Thanks

#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define true 1
#define false 0

int main(int argc,char **args)
{
    int BUF_LENGTH=101;
    int port_no=1800;
    struct sockaddr_in serv_addr,rmt_addr;
    //rmt_addr=malloc(sizeof(struct sockaddr_in));
    char *buffer=malloc(BUF_LENGTH);
    int byte_recv=0;
    int rmt_length=0;

    int sock_id;
    sock_id=socket(AF_INET,SOCK_DGRAM,0);

    if(sock_id<0)
    {
        printf("Error creating socket : %d",sock_id);
        return -1;
    }

    serv_addr.sin_family=AF_INET;
    serv_addr.sin_port=htons(port_no);
    serv_addr.sin_addr.s_addr=inet_addr("127.0.0.1");

    bind(sock_id,(struct sockaddr*)&serv_addr,sizeof(serv_addr));

    printf("Created\n");
    while(true)
    {
        printf("Waiting\n");
        byte_recv=recvfrom(sock_id,buffer,BUF_LENGTH,0,(struct sockaddr*)&rmt_addr,&rmt_length);

        printf("%s\n",buffer);
        if(byte_recv<0)
        {
            printf("Error receiving: %d",byte_recv);
            error("recvfrom");
            return -2;
        }

        printf("%d:%d %s\n",rmt_length,rmt_addr.sin_port,inet_ntoa(rmt_addr.sin_addr));

        byte_recv=sendto(sock_id,buffer,BUF_LENGTH,0,(struct sockaddr*)&rmt_addr,rmt_length); //The segmentation fault comes here

        printf("Bytes sent: %d \n",byte_recv);
        if(byte_recv<0)
            error("sendto");
    }

    free(buffer);
    return 0;
}
Noam M
  • 3,156
  • 5
  • 26
  • 41
Zabi
  • 845
  • 2
  • 9
  • 15

1 Answers1

4

These lines:

error("recvfrom");

error("sendto");

don't do what you think they do. You probably meant to say perror.

Additionally, you aren't initializing rmt_length correctly. Try this:

int rmt_length=sizeof(rmt_addr);

Finally, you are echoing more bytes back than the server receives. Try this:

byte_recv=sendto(sock_id,buffer,byte_recv,0,(struct sockaddr*)&rmt_addr,rmt_length);
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • You were correct, im sorry for my negligence. Now i used perror and its giving me "Address family not supported by protocol" at perror("sendto") – Zabi Sep 12 '11 at 21:27
  • That is because you didn't initialize `rmt_length` properly. See my edited answer. – Robᵩ Sep 12 '11 at 21:33
  • Thanks a lot Rob, it worked. I cant believe i made such silly mistakes but i'm just learning. – Zabi Sep 12 '11 at 21:39