做udp源端口和目的端口必须匹配

do udp source port and destination port have to match?

本文关键字:udp      更新时间:2023-10-16

我正在尝试用c/c++学习套接字编程。我写了两个小的udp发送器。一种是使用bind(),另一种是不使用bind()。我在一个远程IP上建立了这两个程序。同时,我在本地系统上建立了一个小型udp接收器。我试图从两个发送程序发送udp消息到我的本地接收器。但是接收方只能使用bind()从发送方接收消息。它必须与目的地绑定在相同的端口号上。否则,即使使用bind(),它仍然不起作用。但是,当我移动发送程序没有bind()到我的本地系统,并发送消息到"127.0.0.1",它工作。

所以对我来说,似乎在本地发送udp数据包,src端口和dest端口可以是不同的数字。但是当从不同的IP地址发送udp数据包时,发送和接收端口必须具有匹配的端口号。对吗?

这是我的udp发送程序:

#include <iostream>
#include <cstring>
#include <cerrno>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace std;
int main(int argc, char *argv[]){
    if(argc!=2){
        cout<<"need arg"<<endl;
        return 1;
    }
    int sfd = socket(AF_INET, SOCK_DGRAM, 0);
    struct sockaddr_in des;
    des.sin_family = AF_INET;
    des.sin_port = 9999;
    des.sin_addr.s_addr = inet_addr("my ip address"); //I used "127.0.0.1" when I tried it locally.
    /* this is all the difference between the sender with and without bind()
    struct sockaddr_in sai;
    sai.sin_family = AF_INET;
    sai.sin_port = 5001;
    sai.sin_addr.s_addr = INADDR_ANY;
    if(bind(sfd, (struct sockaddr *)&sai, sizeof sai)==-1){
        cout<<"bind:"<<strerror(errno)<<endl;
        _exit(1);
    }
    cout<<"binded successfully"<<endl;
    */
    int byt = sendto(sfd, argv[1], strlen(argv[1])+1, 0, (struct sockaddr *)&des, sizeof des);
    cout<<byt<<endl;
    if(byt<0){
        cout<<"sendto"<<strerror(errno)<<endl;
    }
    return 0;
}

所以对我来说,似乎在本地发送udp数据包,src端口和dest端口可以是不同的数字。

正确的。

但是当从不同的IP地址发送udp数据包时,发送和接收端口必须具有匹配的端口号。对吗?

。它不是。您在应答时所要做的就是确保使用通过recvfrom()返回的接收数据报的源端口作为sendto()中应答数据报的目标端口。

相关文章:
  • 没有找到相关文章