How to set the source port in the UDP socket in c?

前端 未结 4 1809
粉色の甜心
粉色の甜心 2021-02-12 22:05

Can any one tell me how to set the Source port address in the UDP socket ?. My client application needs to send the Packets from the 57002 port to the server port 58007 .

4条回答
  •  面向向阳花
    2021-02-12 22:33

    struct sockaddr_in servaddr,cliaddr;
    sockfd=socket(AF_INET,SOCK_DGRAM,0);
    
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr=inet_addr(argv[1]);
    servaddr.sin_port=htons(32000); //destination port for incoming packets
    
    
    cliaddr.sin_family = AF_INET;
    cliaddr.sin_addr.s_addr= htonl(INADDR_ANY);
    cliaddr.sin_port=htons(33000); //source port for outgoing packets
    bind(sockfd,(struct sockaddr *)&cliaddr,sizeof(cliaddr));
    
    
    
    use sendto with servaddr 
    use recvfrom with cliaddr
    if u check wireshark u will see source port as 33000 and destination port as 32000 for sendto operation
    

提交回复
热议问题