【问题标题】:c Receive / Send same socketc 接收/发送同一个套接字
【发布时间】:2021-07-08 05:50:22
【问题描述】:

我很菜鸟,我有一个问题想知道是否可以在同一个套接字上发送/接收,因为 recv/recvfrom 阻塞了我的代码?

int main(void) {
    struct sockaddr_in si_me, si_other;
    int s, i, slen=sizeof(si_other);
    char buf[BUFLEN];

    if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1)
        die("socket");

    memset((char *) &si_me, 0, sizeof(si_me));
    si_me.sin_family = AF_INET;
    si_me.sin_port = htons(1234);
    si_me.sin_addr.s_addr = htonl(192.168.1.1);

    if (bind(s, &si_me, sizeof(si_me))==-1)
        die("bind");

    recvfrom(s, buf, BUFLEN, 0, &si_other, &slen;
      
   

    close(s);
    return 0;
}

谢谢!

【问题讨论】:

    标签: c sockets udp recv


    【解决方案1】:

    是的,你可以!

    但是请注意,下一次 read 或 recv 可能会读取不同的数据报。 UDP 数据报总是可丢弃的 你仍然可以用 MsgPEEK 或类似的东西标记你的 recv()

    看到这个话题here,我想你不是从那个人那里拿代码吗? :)

    如果你这里的懒惰是题目中的代码

        struct sockaddr_in si_me, si_other;
        int s, i, blen, slen = sizeof(si_other);
        char buf[BUFLEN];
    
        s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
        if (s == -1)
            die("socket");
    
        memset((char *) &si_me, 0, sizeof(si_me));
        si_me.sin_family = AF_INET;
        si_me.sin_port = htons(1234);
        si_me.sin_addr.s_addr = htonl(192.168.1.1);
    
        if (bind(s, (struct sockaddr*) &si_me, sizeof(si_me))==-1)
            die("bind");
    
        int blen = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr*) &si_other, &slen);
        if (blen == -1)
           diep("recvfrom()");
    
        printf("Data: %.*s \nReceived from %s:%d\n\n", blen, buf, inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port));
    
        //send answer back to the client
        if (sendto(s, buf, blen, 0, (struct sockaddr*) &si_other, slen) == -1)
            diep("sendto()");
    
        close(s);
        return 0;
    }```
    

    【讨论】:

    • 谢谢,是的,我拿走了他的代码,但我的不起作用
    猜你喜欢
    • 2016-07-28
    • 2012-10-05
    • 1970-01-01
    • 2014-11-25
    • 2015-11-22
    • 1970-01-01
    • 2013-04-01
    • 1970-01-01
    • 2015-03-09
    相关资源
    最近更新 更多