c 接收/发送相同的套接字 [英] c Receive / Send same socket

查看:34
本文介绍了c 接收/发送相同的套接字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am very noob and i have a question to know if its possible to send/recv on the same socket since recv/recvfrom are blocking my code ?

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

谢谢!

推荐答案

是的,你可以!

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

However Just be cautioned that the next read or recv might read a different datagram. UDP datagrams are always discardable you can still flag your recv() with MsgPEEK or something like that

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

see this topic here , i think you take the code from that guy isn't ? :)

如果你懒惰这里是来自主题的代码

if your lazy here is the code from the topic

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

这篇关于c 接收/发送相同的套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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