微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c 接收/发送相同的套接字

如何解决c 接收/发送相同的套接字

我很菜鸟,我有个问题想知道是否可以在同一个套接字上发送/接收,因为 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,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,&si_other,&slen;
      
   

    close(s);
    return 0;
}

谢谢!

解决方法

是的,你可以!

但是请注意,下一次读取或接收可能会读取不同的数据报。 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,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),(struct sockaddr*) &si_other,&slen);
    if (blen == -1)
       diep("recvfrom()");

    printf("Data: %.*s \nReceived from %s:%d\n\n",inet_ntoa(si_other.sin_addr),ntohs(si_other.sin_port));

    //send answer back to the client
    if (sendto(s,slen) == -1)
        diep("sendto()");

    close(s);
    return 0;
}```

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。