gpt4 book ai didi

c - udp 在同一个套接字上发送和接收

转载 作者:太空狗 更新时间:2023-10-29 16:38:20 25 4
gpt4 key购买 nike

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

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

编辑(代码示例):

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() 该 IP/端口使用与 recvfrom() 相同的套接字,例如:

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 在同一个套接字上发送和接收,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23726931/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com