I've the following code to read multicast message coming from the network, for a specified IP+Port
private static void ReceiveMessages(int port, string ip, CancellationToken token)
{
Task.Factory.StartNew(() =>
{
using (var mUdpClientReceiver = new UdpClient())
{
var mReceivingEndPoint = new IPEndPoint(IPAddress.Any, port);
mUdpClientReceiver.ExclusiveAddressUse = false;
mUdpClientReceiver.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
mUdpClientReceiver.ExclusiveAddressUse = false;
mUdpClientReceiver.Client.Bind(mReceivingEndPoint);
mUdpClientReceiver.JoinMulticastGroup(IPAddress.Parse(ip), 255);
while (!token.IsCancellationRequested)
{
byte[] receive = mUdpClientReceiver.Receive(ref mReceivingEndPoint);
Console.WriteLine("Message received from {0} ",mReceivingEndPoint);
}
}
});
}
I've two network adapter from which I've data coming on this multicast ip+port(confirmed by two instances of wireshark monitoring each network adapter). I see on wireshark a lot of traffic coming on those port+Ip) for both network cards.
The problem is that on my console, I only see messages coming from one network card.
I double checked with netstat, I don't have any other software listening on my port:
So why am I getting traffic from only one of my two network cards?
EDIT:
I even tried the following:
private static void ReceiveMessages(int port, string ip, CancellationToken token, IEnumerable<IPAddress> ipAddresses)
{
foreach (IPAddress ipAddress in ipAddresses)
{
IPAddress ipToUse = ipAddress;
Task.Factory.StartNew(() =>
{
using (var mUdpClientReceiver = new UdpClient())
{
var mReceivingEndPoint = new IPEndPoint(ipToUse, port);
mUdpClientReceiver.ExclusiveAddressUse = false;
mUdpClientReceiver.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
mUdpClientReceiver.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
mUdpClientReceiver.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontRoute, 1);
mUdpClientReceiver.ExclusiveAddressUse = false;
mUdpClientReceiver.Client.Bind(mReceivingEndPoint);
mUdpClientReceiver.JoinMulticastGroup(IPAddress.Parse(ip), 255);
Console.WriteLine("Starting to listen on "+ipToUse);
while (!token.IsCancellationRequested)
{
byte[] receive = mUdpClientReceiver.Receive(ref mReceivingEndPoint);
Console.WriteLine("Message received from {0} on {1}", mReceivingEndPoint,ipToUse);
}
}
});
}
}
I see the "Starting to listen on theCorrectIP" twice(for my two IPs), but it still display only data coming from one network card.
EDIT 2
I did notice something else that is strange too. If I disable the interface on which I receive all data, and then start the software, I now get data from the other interface. If I activate again the interface and restart the software, I still get the traffic on the non-deactivated card.
And I know for sure that I've devices that respond to me, that are connected only to one network(not both)
EDIT 3
Another thing: if I send a message from me(localhost), on all network card that I've, I see them coming on my two network interfaces. BUT, if I start my program twice, only the first programm get messages, not the second one.
Edit 4
Additional info, following the first comment:
I've two ethernet cards, one with the 10.10.24.78 ip, the other with the 10.9.10.234 ip.
It's not me that send data, but network pieces(the port 5353 with this ip is a know multicast address used for mDNS, so I should receive traffic from things like printer, itunes, macs, and some other pieces of software we created). Data are multicasted on the ip
224.0.0.251 and port 5353.
Here is a code that you could use to send data on severals IPs, but like I described, if you start it in local it almost works(except that only one local client receive the message).
private static void SendManuallyOnAllCards(int port, string multicastAddress, IEnumerable<IPAddress> ipAddresses)
{
foreach (IPAddress remoteAddress in ipAddresses)
{
IPAddress ipToUse = remoteAddress;
using (var mSendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
mSendSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership,
new MulticastOption(IPAddress.Parse(multicastAddress)));
mSendSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 255);
mSendSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
var ipep = new IPEndPoint(ipToUse, port);
//IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(multicastAddress), port);
mSendSocket.Bind(ipep);
mSendSocket.Connect(ipep);
byte[] bytes = Encoding.ASCII.GetBytes("This is my welcome message");
mSendSocket.Send(bytes, bytes.Length, SocketFlags.None);
}
}
}
EDIT 5
Here is the result of my route print(Didn't know that command), and on my two IPs, I always receive data on the 10.9.10.234
Edit 6
I tried several other things:
Use a socket to receive instead of the UdpClient --> Didn't worked
Set some addition socketOption on the reader(DontRoute =1, Broadcast=1) -->Didn't worked
Specify the MulticastInterface that the reader Socket has to use(using socketOption MulticastInterface) --> Didn't work
I had the same problem that I wanted to receive multicasts from all my network interfaces. As EJP already said, you need to call JoinMulticastGroup(IPAddress multicastAddr, IPAddress localAddress) on the UdpClient for all network interfaces:
int port = 1036;
IPAddress multicastAddress = IPAddress.Parse("239.192.1.12");
client = new UdpClient(new IPEndPoint(IPAddress.Any, port));
// list of UdpClients to send multicasts
List<UdpClient> sendClients = new List<UdpClient>();
// join multicast group on all available network interfaces
NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface networkInterface in networkInterfaces)
{
if ((!networkInterface.Supports(NetworkInterfaceComponent.IPv4)) ||
(networkInterface.OperationalStatus != OperationalStatus.Up))
{
continue;
}
IPInterfaceProperties adapterProperties = networkInterface.GetIPProperties();
UnicastIPAddressInformationCollection unicastIPAddresses = adapterProperties.UnicastAddresses;
IPAddress ipAddress = null;
foreach (UnicastIPAddressInformation unicastIPAddress in unicastIPAddresses)
{
if (unicastIPAddress.Address.AddressFamily != AddressFamily.InterNetwork)
{
continue;
}
ipAddress = unicastIPAddress.Address;
break;
}
if (ipAddress == null)
{
continue;
}
client.JoinMulticastGroup(multicastAddress, ipAddress);
UdpClient sendClient = new UdpClient(new IPEndPoint(ipAddress, port));
sendClients.Add(sendClient);
}
I am also creating a list of UdpClients so I can send my multicasts on all network interfaces.
I finally found how to do it!
In fact, if I keep exactly the same code, but using it with async methods, it work!!! I just can't understand why it doesn't work with sync method(if someone knows, you're welcome to tell me :) )
Since I've lost 3 days on this, I think it worth an example:
private static void ReceiveAsync(int port, string address, IEnumerable<IPAddress> localAddresses)
{
IPAddress multicastAddress = IPAddress.Parse(address);
foreach (IPAddress localAddress in localAddresses)
{
var udpClient = new UdpClient(AddressFamily.InterNetwork);
udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
udpClient.Client.Bind(new IPEndPoint(localAddress, port));
udpClient.JoinMulticastGroup(multicastAddress, localAddress);
udpClient.BeginReceive(OnReceiveSink,
new object[]
{
udpClient, new IPEndPoint(localAddress, ((IPEndPoint) udpClient.Client.LocalEndPoint).Port)
});
}
}
And the async method:
private static void OnReceiveSink(IAsyncResult result)
{
IPEndPoint ep = null;
var args = (object[]) result.AsyncState;
var session = (UdpClient) args[0];
var local = (IPEndPoint) args[1];
byte[] buffer = session.EndReceive(result, ref ep);
//Do what you want here with the data of the buffer
Console.WriteLine("Message received from " + ep + " to " + local);
//We make the next call to the begin receive
session.BeginReceive(OnReceiveSink, args);
}
I hope that helps ;)
You need to join the multicast group via all available interfaces. By default, the outgoing IGMP JOIN message will be routed according to the unicast routing tables, which will send it out via the 'cheapest' route, using whichever NIC accesses that route. If your multicast group can be sourced via more than one of those routes, you need to iterate.
Related
I have a C# .NET client which listens for UDP multicast messages. I need to receive messages on a single network interface. Sometimes I will not see the messages being received. When I disable the other interfaces, it works.
I attempted to set socket options to a specific interface using code from similar questions on this site, however, I'm unsure if this only affects sending multicast messages and not receiving them?
After my research, I see that the routing table causes this behavior and one solution is to change the routing table, but I prefer not to go that route.
Is it better to join the multicast group on all the interfaces? How would I do that using a UdpClient.
This is the code used to setup my UdpClient:
Getting the interfaces:
public static IEnumerable<NetworkInterface> GetAvailableMulticastInterfaces()
{
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
List<NetworkInterface> availableInterfaces = new List<NetworkInterface>();
foreach (NetworkInterface adapter in nics)
{
IPInterfaceProperties ip_properties = adapter.GetIPProperties();
if (!adapter.GetIPProperties().MulticastAddresses.Any())
continue; // most of VPN adapters will be skipped
if (!adapter.SupportsMulticast)
continue; // multicast is meaningless for this type of connection
if (OperationalStatus.Up != adapter.OperationalStatus)
continue; // this adapter is off or not connected
IPv4InterfaceProperties p = adapter.GetIPProperties().GetIPv4Properties();
if (null == p)
continue; // IPv4 is not configured on this adapter
availableInterfaces.Add(adapter);
}
return availableInterfaces;
}
Setting the Interface:
NetworkInterface networkInterface = Common.Utilities.Network.GetAvailableMulticastInterfaces().Where(nic => nic.Id == attributes.SelectedNetworkInterfaceId).FirstOrDefault();
Getting the Interface Index:
networkInterfaceIndex = (int)IPAddress.HostToNetworkOrder(networkInterface.GetIPProperties().GetIPv4Properties().Index);
Binding the UdpClient:
public void Listen(string multicastGroupAddress, int port, int? networkInterfaceIndex = null)
{
IpAddress = multicastGroupAddress;
Port = port;
_multicastEndPoint = new IPEndPoint(IPAddress.Parse(multicastGroupAddress), port);
Listener = new UdpClient();
Listener.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
if (networkInterfaceIndex != null)
Listener.Client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, networkInterfaceIndex.Value);
var localEndpoint = new IPEndPoint(IPAddress.Any, port);
Listener.Client.Bind(localEndpoint);
Listener.JoinMulticastGroup(IPAddress.Parse(multicastGroupAddress));
while (true)
Process();
}
Ok, so I came back to this and found the right operation to use. One must join on multiple interfaces using
var availableMulticastNics = Utils.GetAvailableMulticastInterfaces();
var listener = new UdpClient();
listener.Client.Bind(new IPEndPoint(IPAddress.Any, endpoint.Port));
foreach (var ni in availableMulticastNics)
{
listener.Client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(multicastEndPoint.Address, ni.GetIPProperties().GetIPv4Properties().Index));
}
// Ready to read socket
Instead of listener.JoinMulticastGroup(ni.GetIPProperties().GetIPv4Properties().Index, multicastEndPoint.Address). Otherwise, I get a SocketException that tells me invalid argument, which someone can shed some light on if they can.
I am writing a couple of functions to allow me to send out a UDP broadcast / multicast using both IPv4 and IPv6. The follow code does this. The problem I have is that it only does this for a single adapter. If I have two network adapters fitted to my PC it doesn’t send the broadcast out on both. Is it possible to have a single socket configured to handle both IPv4 and IPv6 and to send and receive on all NICs? Or do I have to create separate sockets for each IP address?
public void CreateBroadcaster(CancellationToken cancellationToken, int discoveryPort, int advancePort)
{
_cancellationToken = cancellationToken;
_broadcastEndpoint = new IPEndPoint(IPAddress.Broadcast, advancePort);
var epLocal = new IPEndPoint(IPAddress.IPv6Any, discoveryPort);
_broadcaster = new UdpClient(epLocal);
var soc = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp);
soc.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false);
_broadcaster.Client = soc;
_broadcaster.Client.DualMode = true;
_broadcaster.Client.Bind(epLocal);
_broadcaster.EnableBroadcast = true;
_broadcaster.MulticastLoopback = true;
_broadcaster.Client.SetSocketOption(
SocketOptionLevel.IPv6,
SocketOptionName.AddMembership,
new IPv6MulticastOption(IPAddress.Parse("ff02::1")));
}
public void SendPingsOnAdapterLocalSubnets()
{
_broadcaster.Send(_sendData, _sendData.Length, _broadcastEndpoint);
}
You need 2 separate sockets. On the low level, the sockaddr struct will have one or other. IPv4(AF_INET) or IPv6(AF_INET6).
http://www.gnu.org/software/libc/manual/html_node/Address-Formats.html#Address-Formats
I've made a simple chat application in c#.net that sends and receives data between 2 computers.
So, I used this method to send the data:
int port = 11000;
private void send(string data, string ip)
{
Socket sending_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint sending_end_point = null;
byte[] send_buffer = Encoding.ASCII.GetBytes(data);
sending_end_point = new IPEndPoint(IPAddress.Parse(ip), port);
try { sending_socket.SendTo(send_buffer, sending_end_point); }
catch { }
}
And to receive I used this:
string receiveddata = "";
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
UdpClient listener = new UdpClient(port);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, port);
byte[] receive_byte_array;
try
{
receive_byte_array = listener.Receive(ref groupEP);
receiveddata = Encoding.ASCII.GetString(receive_byte_array, 0, receive_byte_array.Length);
}
catch { }
listener.Close();
}
This works without any problems between 2 computers on a LAN, but I would like to know (if possible) how to do the same thing over the Internet.
From what I've searched on the Internet, it seems that I have to use port-forwarding in order to do that, so I already did that, but I don't know what should I do know.
So my question is, how should I change this code (if I have to) so I could send and receive data (UDP) over the internet, assuming I have port-forwarded correctly already and assuming I know the external IPs of both routers?
Thank you in advance.
This should work just fine, as long as your (public) IP-address is correct and the ports are forwarded correctly on your router (meaning, forwarded to the correct private IP, on the correct protocol, in your case UDP).
You are aware that this is UDP though, so it's not reliable data transfer.
I want to to do network discovery using UDP Broadcast in C#. I don't know how to do this. Can you give me advice on how to do it?
I want to do like this tutorial.
It's very simple to make same thing in C#
Server:
var Server = new UdpClient(8888);
var ResponseData = Encoding.ASCII.GetBytes("SomeResponseData");
while (true)
{
var ClientEp = new IPEndPoint(IPAddress.Any, 0);
var ClientRequestData = Server.Receive(ref ClientEp);
var ClientRequest = Encoding.ASCII.GetString(ClientRequestData);
Console.WriteLine("Recived {0} from {1}, sending response", ClientRequest, ClientEp.Address.ToString());
Server.Send(ResponseData, ResponseData.Length, ClientEp);
}
Client:
var Client = new UdpClient();
var RequestData = Encoding.ASCII.GetBytes("SomeRequestData");
var ServerEp = new IPEndPoint(IPAddress.Any, 0);
Client.EnableBroadcast = true;
Client.Send(RequestData, RequestData.Length, new IPEndPoint(IPAddress.Broadcast, 8888));
var ServerResponseData = Client.Receive(ref ServerEp);
var ServerResponse = Encoding.ASCII.GetString(ServerResponseData);
Console.WriteLine("Recived {0} from {1}", ServerResponse, ServerEp.Address.ToString());
Client.Close();
Here is a different solution that is serverless. I had a need to have a bunch of raspberry pis be aware of each other on a network, but had no guarantees of who would be active. So this approach allows everyone to be a client! The complete library is available on GitHub (disclaimer: I created) and that makes this whole process really reaaaally easy for UWP apps.
https://github.com/mattwood2855/WindowsIotDiscovery
This solution assumes that device names are unique and that you want to use JSON strings as the communication protocol, but you could easily just send any other format. Also, in practice try-catch everything ;)
The general mechanism:
Discover your IpAdress
public string IpAddress
{
get
{
var hosts = NetworkInformation.GetHostNames();
foreach (var host in hosts)
{
if (host.Type == HostNameType.Ipv4) return host.DisplayName;
}
return "";
}
}
Set up your listener
var udpPort = "1234";
var socket = new DatagramSocket();
socket.MessageReceived += ReceivedDiscoveryMessage;
await socket.BindServiceNameAsync(udpPort);`
Handle incoming data
async void ReceivedDiscoveryMessage(DatagramSocket socket, DatagramSocketMessageReceivedEventArgs args)
{
// Get the data from the packet
var result = args.GetDataStream();
var resultStream = result.AsStreamForRead();
using (var reader = new StreamReader(resultStream))
{
// Load the raw data into a response object
var potentialRequestString = await reader.ReadToEndAsync();
// Ignore messages from yourself
if (args.RemoteAddress.DisplayName == IpAddress) return;
// Get the message
JObject jRequest = JObject.Parse(potentialRequestString);
// Do stuff with the data
}
}
Send a message
public async void SendDataMessage(string discoveryMessage)
{
// Get an output stream to all IPs on the given port
using (var stream = await socket.GetOutputStreamAsync(new HostName("255.255.255.255"), udpPort))
{
// Get a data writing stream
using (var writer = new DataWriter(stream))
{
// Write the string to the stream
writer.WriteString(discoveryMessage);
// Commit
await writer.StoreAsync();
}
}
}
The idea would be to send a discovery message containing your ip address and name. Then in the receive message function add the ip-name pairs to a List of devices. Add a little logic to avoid duplicates and update Ip address if the ip changes for a given name.
As a bonus, you can have each device send the list of devices they know about. This allows you to minimize udp traffic by not responding when the sender is aware of you. You can even have the receiver compare the list against their own list to discover other devices.
Redundancy is your friend with UDP, there is no guarantee that a packet will be delivered.
I know it's old but someone may still need this...The accepted answer is great but with this little tweak on the server side it's even better.
Fix for the Ilya Suzdalnitski comment (locks up on the second Client.Receive call):
var responseData = Encoding.ASCII.GetBytes("someData");
while (true)
{
var server = new UdpClient(8888);
var clientEp = new IPEndPoint(IPAddress.Any, 0);
var clientRequestData = server.Receive(ref clientEp);
var clientRequest = Encoding.ASCII.GetString(clientRequestData);
Console.WriteLine($"Recived {clientRequest} from {clientEp.Address}, sending
response: {responseData}");
server.Send(responseData, responseData.Length, clientEp);
server.Close();
}
Because after each response the server is closed and recreated, it can work endlessly without locking.
I had the same question but it was not that easy for me as the answer that #rufanov suggests.
Here some situation I had:
Since my application is running normally in a computer that has several network interfaces, I had the problem that the broadcast message was sent only in one of the adapters. To solve this situation I had to get first all the network adapter list and go one by one sending the broadcast message and receiving the answer message.
It is important that you bind the correct localIpEndPoint to your adapters ip address, otherwise you will have problems with the broadcast address by sending.
After some reserch and work I got to this solution. This code corresponds to the server side and will make the network discovery of all devices answering to the braodcast message.
public static void SNCT_SendBroadcast(out List<MyDevice> DevicesList)
{
DevicesList = new List<MyDevice>();
byte[] data = new byte[2]; //broadcast data
data[0] = 0x0A;
data[1] = 0x60;
IPEndPoint ip = new IPEndPoint(IPAddress.Broadcast, 45000); //braodcast IP address, and corresponding port
NetworkInterface[] nics = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces(); //get all network interfaces of the computer
foreach (NetworkInterface adapter in nics)
{
// Only select interfaces that are Ethernet type and support IPv4 (important to minimize waiting time)
if (adapter.NetworkInterfaceType != NetworkInterfaceType.Ethernet) { continue; }
if (adapter.Supports(NetworkInterfaceComponent.IPv4) == false) { continue; }
try
{
IPInterfaceProperties adapterProperties = adapter.GetIPProperties();
foreach (var ua in adapterProperties.UnicastAddresses)
{
if (ua.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
//SEND BROADCAST IN THE ADAPTER
//1) Set the socket as UDP Client
Socket bcSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); //broadcast socket
//2) Set socker options
bcSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
bcSocket.ReceiveTimeout = 200; //receive timout 200ms
//3) Bind to the current selected adapter
IPEndPoint myLocalEndPoint = new IPEndPoint(ua.Address, 45000);
bcSocket.Bind(myLocalEndPoint);
//4) Send the broadcast data
bcSocket.SendTo(data, ip);
//RECEIVE BROADCAST IN THE ADAPTER
int BUFFER_SIZE_ANSWER = 1024;
byte[] bufferAnswer = new byte[BUFFER_SIZE_ANSWER];
do
{
try
{
bcSocket.Receive(bufferAnswer);
DevicesList.Add(GetMyDevice(bufferAnswer)); //Corresponding functions to get the devices information. Depends on the application.
}
catch { break; }
} while (bcSocket.ReceiveTimeout != 0); //fixed receive timeout for each adapter that supports our broadcast
bcSocket.Close();
}
}
}
catch { }
}
return;
}
For working example, see that project:https://github.com/xmegz/MndpTray
The server periodically sends broadcast messages. The client side receive and process them. Many host information (Os version, IP address, Network interface, etc..) send trought.
udp broadcast cdp lldp
Platform: Windows 2003 R2, C#
I have an application that sends UDP messages to other instances of itself, running on the same computer and on other computers. This is working fine. But, on some computers, the listener cannot hear messages that other thread/process on the same computer has transmitted. The message is broadcast ok, and other machines on the network hear the message, but a listener on the same machine cannot hear the message.
The weird part is that this happens on SOME machines in my test environment, but not all.
Edit: All machine that fail have the Check Point VPN-1 Securemote client software installed. I took a machine that was working, installed the VPN client, and now it does not work. Note that I am not connected to any VPN hosts, I just have the client installed.
All machines have a single network adapter, subnet mask of 255.255.255.0, and IP address of 10.3.10.xxx.
Here is a test class that demonstrates the problem. The user types some text, and it gets sent to 10.3.10.255. On some machines, the ReceiveFrom returns, and on others it does not. I am calling Controller("10.3.10.255",33333)
public class Controller
{
public Controller(IPAddress broadcastAddress, int port)
{
_broadcastAddress = broadcastAddress;
_port = port;
}
public void Start()
{
Socket s = null;
try
{
IPEndPoint _listenEndpoint = new IPEndPoint(IPAddress.Any, _port);
_broadcastEndpoint = new IPEndPoint(_broadcastAddress, _port);
s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 10);
s.EnableBroadcast = true;
s.Bind(_listenEndpoint);
SocketState receiveState = new SocketState();
receiveState.s = s;
receiveState.buf = new byte[1024];
EndPoint lep = (EndPoint)_broadcastEndpoint;
s.BeginReceiveFrom(receiveState.buf, 0, receiveState.buf.Length, SocketFlags.None, ref lep, new AsyncCallback(OnReceive), receiveState);
bool done = false;
while (!done)
{
string msg = Console.In.ReadLine();
byte[] msg_bytes = Encoding.ASCII.GetBytes(msg);
if (msg_bytes.Length == 0)
done = true;
else
{
Console.Out.WriteLine("---> {0}", msg);
s.SendTo(msg_bytes, msg_bytes.Length, SocketFlags.None, new IPEndPoint(_broadcastAddress, _port));
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
if (s != null)
s.Close();
}
}
internal void OnReceive(IAsyncResult ar)
{
SocketState state = ar.AsyncState as SocketState;
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 0);
EndPoint ep = (EndPoint)ipep;
int nRead = state.s.EndReceiveFrom(ar, ref ep);
IPEndPoint myipep = ep as IPEndPoint;
Console.WriteLine("<--- {0} {1}", myipep.Address.ToString(), System.Text.Encoding.ASCII.GetString(state.buf, 0, nRead));
EndPoint lep = (EndPoint)_broadcastEndpoint;
state.s.BeginReceiveFrom(state.buf, 0, state.buf.Length, SocketFlags.None, ref lep, new AsyncCallback(OnReceive), state);
}
IPAddress _broadcastAddress;
int _port = 0;
IPEndPoint _broadcastEndpoint;
}
internal class SocketState
{
internal Socket s;
internal byte[] buf;
}
What does the Check Point VPN-1 Securemote client software do? It sounds like it might do some sort of firewalling in which case it would be blocking data coming in on the specified port.
1) If you can configure it to allow data through that port, then you should be good to go.
2) Another less likely option is that maybe it is listening on the port that you are trying to listen to in which case it is receiving the udp packet as opposed to your application. I would expect you app to throw an error though in that case.
In the SecureClient settings (right click on the tray icon and select Settings), on the Security tab you can enable an option to "log all connections that are blocked by the desktop security policy".
You should then be able to see if that's indeed what is blocking your application - if it is, you'll have to get the default policy changed to allow your application. I'm not sure how to do that - I've never administered the server side of SecureRemote, but I'm sure Check Point can help you out if your network admins can't.