UDP服务器出现分段错误 [英] UDP Server giving Segmentation Fault

查看:103
本文介绍了UDP服务器出现分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用UDP编写了以下回显服务器,但是我不知道为什么它在sendto函数中给我带来Segmentation Fault,它可以正常运行,但是在将数据发送回客户端时遇到问题.我已经尝试寻找问题了几个小时,但无处可寻.有人可以指出错误还是我可能做错了什么. 谢谢

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;
}

推荐答案

这些行:

error("recvfrom");

error("sendto");

不做您认为他们做的事.您可能想说 perror .

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

此外,您没有正确初始化rmt_length.试试这个:

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);

这篇关于UDP服务器出现分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆