简体   繁体   中英

Port to Port data transfer with UDP

I'm working on this project where the source and destination ports are specified for sending a message via a UDP socket in C++. I've got the TCP portion of the project working fine, but I don't understand how to specify both the source and destination ports when setting this up.

The way I would know how to do it is the "receiver" sets up a recvfrom() call, with the port that the "sender" will also use in the sendto() command... but it would need to be the same port.

So, given that I need port x on the "receiver" to talk to port y on the "sender", how would I do that?

Thanks

You can define a source port when you call bind on the sender side. For instance:

sockfd = socket(AF_INET, SOCK_STREAM, 0); 
if (sockfd < 0) { /*error*/}

sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = htonl(INADDR_ANY);
sin.sin_port = htons(source_port);  // here

int res = bind(sockfd,(struct sockaddr*)&sin, sizeof(sin));
if (res < 0) { /*error*/}

And the destination port goes into the sockaddr parameter passed to sendto .

If this is one-to-one mapping, ie one source talks to one destination, then simply bind(2) the local port and connect(2) to the remote IP and port (contrary to common misconception you can connect UDP sockets). Do that on both sides (with appropriate remote and local IPs/ports of course), and now you can just use recv(2) and send(2) without explicit addressing.

If one side needs to wait for the other to send the first packet, then extract source address/port received with recvfrom(2) , and then connect(2) to it.

If, on the other hand, one side acts as a multi-client server, then do same bind(2) / connect(2) dance on the client, but only do bind(2) to local port and then use recvfrom(2) / sendto(2) on the server.

If you need simultaneous duplex communication, then you should use sockets in blocking mode -- fcntl(...O_NONBLOCK...) , and use select() to determine if your socket is writable or readable or both. Here is a nice example on how this can be done http://www.lowtek.com/sockets/select.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM