473,608 Members | 2,287 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Finding server with broadcast

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(AddressF amily.InterNetw ork,
SocketType.Dgra m, ProtocolType.Ud p);
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.Broad cast, 48000 ) );
}

Client:
Socket client = new Socket(AddressF amily.InterNetw ork,
SocketType.Dgra m, ProtocolType.Ud p);
client.Connect( new IPEndPoint( IPAddress.Broad cast, 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.

Nov 17 '05 #1
6 10304
pe*****@home.se wrote:
I did this simple quick-hack:
see below
Server:
Socket server = new Socket(AddressF amily.InterNetw ork,
SocketType.Dgra m, ProtocolType.Ud p);
server.Bind( new IPEndPoint( IPAddress.Any, 48000 ) );

while(true)
{
byte[] buffer = new byte[1000];
server.Receive( buffer);
use ReceiveFrom here. this will give you an IPEndPoint with the address of
the sending client.
Console.Write(" Server got: " + buffer[0]);
//Next line crash cause some permission error.
server.SendTo( new byte[] {2},
new IPEndPoint( IPAddress.Broad cast, 48000 ) );
don't send the response back by broadcast. you can send it directly to the
client using the above IPEndPoint.
}

Client:
Socket client = new Socket(AddressF amily.InterNetw ork,
SocketType.Dgra m, ProtocolType.Ud p);
client.Connect( new IPEndPoint( IPAddress.Broad cast, 48000 ));
not sure if Connect should be used for a connectionless (UDP) socket. I
think it should work, but I always prefer the SendTo and ReceiveFrom
functions for UDP. also you might want to use port 0 for the client. this
way some free source port will be allocated automatically. in your case, if
client and server are running on the same system, they will both access
port 48000, which might fail.

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();


hth,
Max

Nov 17 '05 #2
Markus Stoeger wrote:
not sure if Connect should be used for a connectionless (UDP) socket. I
think it should work, but I always prefer the SendTo and ReceiveFrom
functions for UDP. also you might want to use port 0 for the client. this
way some free source port will be allocated automatically. in your case, if
client and server are running on the same system, they will both access
port 48000, which might fail.


Thank you, I followed your instructions and now the code works. I also
tried to use port 0 on the client, but then the server didn't received
any message (btw, should I use bind on the server?).

This is the code that have so far. Works pretty well:

Server:
//Start server
Socket server = new Socket(AddressF amily.InterNetw ork,
SocketType.Dgra m, ProtocolType.Ud p);
Console.Write(" Running server..." + Environment.New Line);
server.Bind( new IPEndPoint( IPAddress.Any, 48000 ) );

while(true)
{
IPEndPoint sender = new IPEndPoint(IPAd dress.Any, 0);
EndPoint tempRemoteEP = (EndPoint)sende r;
byte[] buffer = new byte[1000];
//Recive message from anyone.
server.ReceiveF rom(buffer, ref tempRemoteEP);

Console.Write(" Server got '" + buffer[0] +
"' from " + tempRemoteEP.To String() +
Environment.New Line);

Console.Write(" Sending '2' to " + tempRemoteEP.To String() +
Environment.New Line);

//Replay to client
server.SendTo( new byte[] {2},
tempRemoteEP );
}

Client:
Socket client = new Socket(AddressF amily.InterNetw ork,
SocketType.Dgra m,
ProtocolType.Ud p);

IPEndPoint AllEndPoint = new IPEndPoint( IPAddress.Broad cast, 48000 );

//Allow sending broadcast messages
client.SetSocke tOption(SocketO ptionLevel.Sock et,
SocketOptionNam e.Broadcast, 1);

//Send message to everyone
client.SendTo( new byte[] {1}, AllEndPoint );
Console.Write(" Client send '1' to " + AllEndPoint.ToS tring() +
Environment.New Line);

IPEndPoint sender = new IPEndPoint(IPAd dress.Any, 0);
EndPoint tempRemoteEP = (EndPoint)sende r;
byte[] buffer = new byte[1000];

string serverIp;

try
{
//Recieve from server. Don't wait more than 3000 milliseconds.
client.SetSocke tOption(SocketO ptionLevel.Sock et,
SocketOptionNam e.ReceiveTimeou t, 3000);
client.ReceiveF rom(buffer, ref tempRemoteEP);
Console.Write(" Client got '" + buffer[0] + "' from " +
tempRemoteEP.To String()+ Environment.New Line);

//Get server IP (ugly)
serverIp = tempRemoteEP.To String().Split( ":".ToCharArray (), 2)[0];
}
catch
{
//Timout. No server answered.
serverIp = "?";
}

Console.Write(" ServerIp: " + serverIp + Environment.New Line);

Nov 17 '05 #3
pe*****@home.se wrote:
Thank you, I followed your instructions and now the code works. I also
tried to use port 0 on the client, but then the server didn't received
any message
I think you have to bind the port on the client side also. Then it should
work with port 0 (haven't tried it right now though).
(btw, should I use bind on the server?).


Yes you have to, otherwise it doesn't know where to listen for the
broadcast.

Have you tested this code on a system with multiple network interfaces yet?
I did something like that a while ago and as far as I remember such a
broadcast is only sent out on one interface, not on all. You have to lookup
the network interface addresses and send a broadcast on each of them. You
can use the Dns functions to resolve your computers hostname, that should
give you all available local network interface addresses.

Max

Nov 17 '05 #4
Markus Stoeger wrote:
I think you have to bind the port on the client side also. Then it should
work with port 0 (haven't tried it right now though).
I added a bind call in the client code. It failed, as expected, cause
two programs where listening on port 48000 at the same time. I then
changed to port 0. No program crashed, but the client didn't find the
server.
Have you tested this code on a system with multiple network interfaces yet?
I did something like that a while ago and as far as I remember such a
broadcast is only sent out on one interface, not on all. You have to lookup
the network interface addresses and send a broadcast on each of them. You
can use the Dns functions to resolve your computers hostname, that should
give you all available local network interface addresses.


Good point. I could get all addresses by calling:
string hostname = System.Net.Dns. GetHostName();
IPHostEntry allLocalNetwork Addresses = Dns.Resolve(hos tname);

But how do I use that information? Creating EndPoint like this:

foreach(IPAddre ss ip in allLocalNetwork Addresses.Addre ssList)
{
IPEndPoint AllEndPoint = new IPEndPoint( ip, Port );

will only make the client call it self to find the server. In the
original code I do this:

IPEndPoint AllEndPoint = new IPEndPoint( IPAddress.Broad cast, Port );

How do I get the broadcast address for each network?

PEK

Nov 17 '05 #5
pe*****@home.se wrote:
Markus Stoeger wrote:
Good point. I could get all addresses by calling:
string hostname = System.Net.Dns. GetHostName();
IPHostEntry allLocalNetwork Addresses = Dns.Resolve(hos tname);

But how do I use that information?


I don't have the source code here right now, but I think you have to create
one socket for each ip address that you get from Dns.Resolve. Then bind the
sockets to these addresses (instead of binding them to IPAddress.Any).
When you call SendTo, use IPAddress.Broad cast as destination.
This way it will be sent out as broadcast on exactly the interface you have
bound the socket to. You'll also have to call ReceiveFrom on each socket.
I think you have to bind the port on the client side also. Then it should
work with port 0 (haven't tried it right now though).


I added a bind call in the client code. It failed, as expected, cause
two programs where listening on port 48000 at the same time. I then
changed to port 0. No program crashed, but the client didn't find the
server.


It should work.. maybe there is another problem? Take a look at the Bind
description on MSDN: http://tinyurl.com/cqoce
It says "If you do not care which local port is used, you can create an
IPEndPoint using 0 for the port number. In this case, the service provider
will assign an available port number between 1024 and 5000."

hth,
Max

Nov 17 '05 #6
Markus Stoeger wrote:
I don't have the source code here right now, but I think you have to create
one socket for each ip address that you get from Dns.Resolve. Then bind the
sockets to these addresses (instead of binding them to IPAddress.Any).
When you call SendTo, use IPAddress.Broad cast as destination.
This way it will be sent out as broadcast on exactly the interface you have
bound the socket to. You'll also have to call ReceiveFrom on each socket.
Yes, of course. I should have figured out that myself.

It should work.. maybe there is another problem? Take a look at the Bind
description on MSDN: http://tinyurl.com/cqoce
It says "If you do not care which local port is used, you can create an
IPEndPoint using 0 for the port number. In this case, the service provider
will assign an available port number between 1024 and 5000."


My mathematical knowledge tells me that 48000 > 5000 :-). Changing to
port 4800 solved the final problem. To those that are interested, this
is the code:

Server:
//Start server
const int Port = 4800;
Socket server = new Socket(AddressF amily.InterNetw ork,
SocketType.Dgra m, ProtocolType.Ud p);
Console.Write(" Running server..." + Environment.New Line);
server.Bind( new IPEndPoint( IPAddress.Any, Port ) );

while(true)
{
IPEndPoint sender = new IPEndPoint(IPAd dress.Any, 0);
EndPoint tempRemoteEP = (EndPoint)sende r;
byte[] buffer = new byte[1000];
//Recive message from anyone.
//Server could crash here if there is another server
//on the network listening at the same port.
server.ReceiveF rom(buffer, ref tempRemoteEP);

Console.Write(" Server got '" + buffer[0] +
"' from " + tempRemoteEP.To String() + Environment.New Line);

Console.Write(" Sending '2' to " + tempRemoteEP.To String() +
Environment.New Line);

//Replay to client
server.SendTo( new byte[] {2},
tempRemoteEP );
}

Client:
const int Port = 4800;
string serverIp = "?";

//Get all addresses
string hostname = System.Net.Dns. GetHostName();
IPHostEntry allLocalNetwork Addresses = Dns.Resolve(hos tname);

//Walk thru all network interfaces.
foreach(IPAddre ss ip in allLocalNetwork Addresses.Addre ssList)
{
Socket client = new Socket(AddressF amily.InterNetw ork,
SocketType.Dgra m, ProtocolType.Ud p);

//Bind on port 0. The OS will give some port between 1025 and 5000.
client.Bind( new IPEndPoint( ip, 0 ) );

//Create endpoint, broadcast.
IPEndPoint AllEndPoint = new IPEndPoint( IPAddress.Broad cast, Port );

//Allow sending broadcast messages
client.SetSocke tOption(SocketO ptionLevel.Sock et,
SocketOptionNam e.Broadcast, 1);

//Send message to everyone on this network
client.SendTo( new byte[] {1}, AllEndPoint );
Console.Write(" Client send '1' to " + AllEndPoint.ToS tring() +
Environment.New Line);

try
{
//Create object for the server.
IPEndPoint sender = new IPEndPoint(IPAd dress.Any, 0);
EndPoint tempRemoteEP = (EndPoint)sende r;
byte[] buffer = new byte[1000];

//Recieve from server. Don't wait more than 3000 milliseconds.
client.SetSocke tOption(SocketO ptionLevel.Sock et,
SocketOptionNam e.ReceiveTimeou t, 3000);

//Recive message, save wherefrom in tempRemoteIp
client.ReceiveF rom(buffer, ref tempRemoteEP);
Console.Write(" Client got '" + buffer[0] + "' from " +
tempRemoteEP.To String()+ Environment.New Line);

//Get server IP (ugly)
serverIp = tempRemoteEP.To String().Split( ":".ToCharArray (), 2)[0];

//Don't try any more networkss
break;
}
catch
{
//Timout. No server answered. Try next network.
}
}

Console.Write(" ServerIp: " + serverIp + Environment.New Line);
Thanks for your excellent support Max!

PEK

Nov 17 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1364
by: David Hofmann | last post by:
I'm setting up 2 database servers. The first is on our local network which is our staging server. The second is an external server setup at my hosting company. On a nightly bases I want to copy all the data from the local Postgre database to the production server at hosting company overriding whatever was there previously. Does anyone have any suggestions on an easy was to do this ? ...
1
3163
by: Doug | last post by:
The html below shows DataList "DiscountList" nested within DataList "EventItemList". DiscountList contains a Label control. I'm trying to find the label, using FindControl, during EventList_ItemCreated (below the html), but it's always <undefined value> (null). Everything else works fine. Eventually I need to set the value of the label depending up the Count of the DataView "dvDiscount". For now I'll settle for just finding the damn...
1
1110
by: Aussie Rules | last post by:
Hi, I have a classic client server app. When the client is installed on the PC I would like the client application to some how 'find' the server or servers that host the server logic. Kind of like how the SQL tools, can list all the SQL servers in the network. My thoughts are to have the server running some sort of web service,
6
2041
by: Anony Mous | last post by:
Hi, We've got some clients that are concerned about running Postgresql 7.3.4 on a Win2k Server box, alongside MS SQL Server. I've been running pg on my XP machines for a long time now (with cygwin) and never had any sort of problem. The db is fast and stable. Does anyone have any experience that would give some weight to our client's concerns? Would there be any potential conflict between the postmaster and MS SQL Server? Your...
4
1733
by: ruben | last post by:
Hi: I'm getting this error when accessing a table with certain WHERE condition: "server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request. The connection to the server was lost. Attempting reset: Failed." I've read through the posts but found no answer to the problem.
2
6592
by: Gunnar_Frenzel | last post by:
Hello, this might be an easy question, but I don't have any handy solution at hand. I have an application that is supposed to send UDP broadcast. So far so easy, I did: Socket sockSendBroadcast = null; IPEndPoint ipeSendBroadcast = null; ipeSendBroadcast = new IPEndPoint(IPAddress.Broadcast, iSomePort);
0
2803
by: Crisco www.misericordia.com.br | last post by:
Hi I m working on WEBRADIO Software. im using Windows media encoder 9 SDK on Windows 2003 server using VB.NET. My current scenario is my soundcard . My application will push my server the live audio on specific port. I am using Windows media encoder sdk sample (entire code), currently i
2
1488
by: sunny | last post by:
I need to find my server over the network!!! so my installer installs client on one machine and server on other machine on the same network. How can i do that??? How can my client know where my server is??? please help sunny a newbee!!!!
1
3899
by: viswanathtvs | last post by:
java.util.NoSuchElementException javax.faces.el.EvaluationException: java.util.NoSuchElementException at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102) at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102) at javax.faces.component.UICommand.broadcast(UICommand.java:387) at...
0
8063
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8475
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8148
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8338
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6013
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5475
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3962
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2474
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1594
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.