Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: UdpSocket question  (Read 2176 times)

0 Members and 1 Guest are viewing this topic.

Kyoya

  • Newbie
  • *
  • Posts: 7
    • View Profile
UdpSocket question
« on: May 05, 2017, 03:05:57 pm »
Hi. I have a question more related to network functionality rather than to programming.

Code below is responsible for sending packet:

std::string ipString;
sf::UdpSocket socket;
sf::Packet packet;
unsigned short port;

std::cout << "Set recipient IP: ";
std::cin >> ipString;
std::cout << "Set recipient port: ";
std::cin >> port;
sf::IpAddress ipAddress(ipString);

socket.send(packet, ipAddress, port);
 

As a sender I have to set IP address of recipient and recipient's port.

And this code is responsible for receiving packet:

unsigned short port;
sf::UdpSocket socket;
sf::IpAddress ipAddress;
sf::Packet packet;

std::cout << "Set server port: ";
std::cin >> port;
socket.setBlocking(false);
socket.bind(port);
while(true)
{
     if(socket.receive(packet, ipAddress, port) == sf::Socket::Done)
     {
           std::cout << "IP Address: " << ipAddress << " port: " << port << std::endl;
     }
}
 

After receiving a packet, variables ipAddress and port are filled with sender's IP and port number.

So let's say, I want to set server at port 4096 and try to send packet from client. So as a client I set server's IP and port number. Everything is ok, my packet went to server. But here is my question. Server's output is good as far as IP address is concerned, but port number is different than 4096. I presume that it should be like that and everything is good, but I don't understand why client's port is different than 4096. I'm looking forward your answer.

Laurent

  • Administrator
  • Hero Member
  • *****
  • Posts: 32498
    • View Profile
    • SFML's website
    • Email
Re: UdpSocket question
« Reply #1 on: May 05, 2017, 04:01:14 pm »
When you send something with a UDP socket, the system binds it to a random port so that it is ready to receive a response. There is no relation between the ports used on server side (which is explicitly set by your code) and on client side (which is randomly chosen by the OS).
Laurent Gomila - SFML developer

Kyoya

  • Newbie
  • *
  • Posts: 7
    • View Profile
Re: UdpSocket question
« Reply #2 on: May 05, 2017, 05:13:45 pm »
Thank you for a clear answer. I get it know.

 

anything