[英]c Receive / Send same socket
我很菜鳥,我有一個問題想知道是否可以在同一個套接字上發送/接收,因為 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;
}
謝謝!
是的你可以 !
但是請注意,下一次 read 或 recv 可能會讀取不同的數據報。 UDP 數據報總是可以丟棄的,你仍然可以用 MsgPEEK 或類似的東西標記你的 recv()
在這里看到這個話題,我想你不是從那個人那里拿的代碼嗎? :)
如果您的懶惰是該主題的代碼
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;
}```
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.