c - udp 在同一个套接字上发送和接收 [英] c - udp send and receive on the same socket

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

问题描述

我想在同一个套接字上发送和接收数据包,是否可能或者我必须创建两个套接字,一个发送一个接收?如果是的话,你能给我举个例子吗?

I would like to send and receive packets on the same socket, is it possible or I have to create two socket, one to send and one to receive? If yes, can you give me an example?

另一个问题:如何从接收到的数据包中获取源IP?

Another question: how can I get the source ip from a received packet?

编辑(代码示例):

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

    if (recvfrom(s, buf, BUFLEN, 0, &si_other, &slen)==-1)
       diep("recvfrom()");
    printf("Data: %s \nReceived from %s:%d\n\n", buf, inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port));

    //now I want the server to answer back to the client

    close(s);
    return 0;
}

推荐答案

是的,您可以使用同一个套接字进行发送和接收.recvfrom() 告诉您发件人的 IP/端口.只需 sendto() 使用与 recvfrom() 相同的套接字的 IP/端口,例如:

Yes, you can use the same socket for sending and receiving. recvfrom() tells you the IP/port of the sender. Simply sendto() that IP/port using the same socket that you use with recvfrom(), eg:

int main(void) {
    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 - udp 在同一个套接字上发送和接收的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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