1

I want to make sure that I understand the concept we have example.exe and we will run it 5 times or more on the same computer

example.exe will create a pear (which has a sending and receiving socket) and the sending socket sends on a fixed port and the receiving socket receive on the same port

my question is that when running example.exe 5 times 5 peers will be created on the same "machine" with the same fixed port !!! how that comes ! and i tried the code and it is working on the machine which means the same Ip address!

here are some code

Receiving Socket

sockaddr_in RecvAddr;
RecvAddr.sin_family = AF_INET;
RecvAddr.sin_port = htons(PORT);
RecvAddr.sin_addr.s_addr = htonl(INADDR_ANY);

cout << RecvAddr.sin_addr.s_addr << endl;


int broadcastValue = 1;
if (setsockopt(receivingSocket, SOL_SOCKET, SO_REUSEADDR, (char*)&broadcastValue, sizeof(broadcastValue)) == SOCKET_ERROR)
    exit(EXIT_FAILURE);

int iResult = 0;
iResult = bind(receivingSocket, (SOCKADDR *)& RecvAddr, sizeof (RecvAddr));
if (iResult != 0) {
    exit(EXIT_FAILURE);

Sending Socket

sockaddr_in destinationAddress;
destinationAddress.sin_family = AF_INET;
destinationAddress.sin_addr.s_addr = INADDR_BROADCAST;
destinationAddress.sin_port = htons((unsigned short)PORT);

if (sendto(sendingSocket, message.c_str(), message.length(), 0, (struct sockaddr*) &destinationAddress, sizeof(destinationAddress)) == SOCKET_ERROR)
{

    exit(EXIT_FAILURE);
}
Rehab Reda
  • 193
  • 7
  • 16
  • Thank you berkus :) I have a question if we want to make the same functionality using TCP will it be possible ? peers have same port and we want all of them to be connected ? how could a peer connect to all of them and they have the same port without using broadcast( it think it doesn't exist in tcp ) – Rehab Reda Apr 08 '14 at 06:11
  • There is no point in doing this, SO_REUSEADDR with tcp connections is usually used for rebinding a socket over an already dead (zombie) one. – berkus Apr 08 '14 at 07:22
  • Thank you berkus :) i understand the so_reuseaddr will enable to have the same address but i can't understand its concept ? how this canbe done ? I imagine that it close one port and it give it to a peer and then close it and open it to another right or what ? – Rehab Reda Apr 08 '14 at 11:20
  • You can't open "another one" it really. It's not a "resource", it's an identifier, like a post address 127.0.0.1:5523 is like street, house and apartment number. – berkus Apr 08 '14 at 12:08
  • so how so_reuseaddr works ? how it enables more than one peer to have the same port number ?again thank you so much :) – Rehab Reda Apr 08 '14 at 14:27
  • There's a fairly good explanation in this post on SO, take your time to read it. http://stackoverflow.com/questions/14388706/socket-options-so-reuseaddr-and-so-reuseport-how-do-they-differ-do-they-mean-t – berkus Apr 08 '14 at 16:21

0 Answers0