P
pekspro
I need some code that gets the address from a server. I read somewhere
that you could do this by starting some broadcast server using UDP. The
client should send an broadcast message, and when the server answering
the client gets the address. But how do I implement this?
I did this simple quick-hack:
Server:
Socket server = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
server.Bind( new IPEndPoint( IPAddress.Any, 48000 ) );
while(true)
{
byte[] buffer = new byte[1000];
server.Receive(buffer);
Console.Write("Server got: " + buffer[0]);
//Next line crash cause some permission error.
server.SendTo( new byte[] {2},
new IPEndPoint( IPAddress.Broadcast, 48000 ) );
}
Client:
Socket client = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
client.Connect(new IPEndPoint( IPAddress.Broadcast, 48000 ));
Console.Write("Client send: 1");
client.Send( new byte[] {1} );
byte[] buffer = new byte[1000];
client.Receive(buffer);
Console.Write("Client got: " + buffer[0]);
client.Close();
To my surprise the code almost worked
. The server receive the
message from the client, but it fails when sending data. And even if it
did it doesn't help the client cause will not know who send the
message.
I'm thankful for any ideas. What I'm looking for is a way to find the
address of a server. It doesn't need to be perfect, it will just give
the users a hint which address to use for the real application.
that you could do this by starting some broadcast server using UDP. The
client should send an broadcast message, and when the server answering
the client gets the address. But how do I implement this?
I did this simple quick-hack:
Server:
Socket server = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
server.Bind( new IPEndPoint( IPAddress.Any, 48000 ) );
while(true)
{
byte[] buffer = new byte[1000];
server.Receive(buffer);
Console.Write("Server got: " + buffer[0]);
//Next line crash cause some permission error.
server.SendTo( new byte[] {2},
new IPEndPoint( IPAddress.Broadcast, 48000 ) );
}
Client:
Socket client = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
client.Connect(new IPEndPoint( IPAddress.Broadcast, 48000 ));
Console.Write("Client send: 1");
client.Send( new byte[] {1} );
byte[] buffer = new byte[1000];
client.Receive(buffer);
Console.Write("Client got: " + buffer[0]);
client.Close();
To my surprise the code almost worked

message from the client, but it fails when sending data. And even if it
did it doesn't help the client cause will not know who send the
message.
I'm thankful for any ideas. What I'm looking for is a way to find the
address of a server. It doesn't need to be perfect, it will just give
the users a hint which address to use for the real application.