Broadcasting UDP message from C# to Python - c#

I'm trying to send a broadcast message from a C# app on one machine to a Python script on another. If I specify the Python machine's IP as my endpoint, I can send a message just fine. Here's how I'm sending my message:
const int PORT = 12345;
using (var sock = new UdpClient())
{
var endpoint = new IPEndPoint(IPAddress.Parse(remoteIP), PORT);
//var endpoint = new IPEndPoint(IPAddress.Broadcast, PORT);
byte[] bytes = Encoding.UTF8.GetBytes("hello, world!");
sock.Send(bytes, bytes.Length, endpoint);
}
On the Python side, I'm receiving as follows:
import socket
PORT = 12345
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('', PORT))
#sock.bind(('<broadcast>', PORT))
while 1:
data,addr = sock.recvfrom(1024)
if not data: break
print(data)
I can send my message from one machine to another successfully. However, I have multiple machines to which I want my message to go (UDP broadcast), but when I use IPAddress.Broadcast as my endpoint, Python doesn't receive my message. I've also tried binding my Python socket to <broadcast>, but that doesn't help, and binding to my C# machine's IP gives me the error socket.gaierror: [Errno -3] Temporary failure in name resolution.
I don't know if this is an issue of C# not sending the broadcast or of Python not receiving it.

You can use a network analyzer such as Wireshark to verify the operation of your networking code. I suspect that if you do, you will find that no broadcast datagram is actually set.
Lacking a good, complete code example it's hard to say for sure what the reason would be. But the cause of this would most likely be because you have not set the Socket.EnableBroadcast property for your socket. It defaults to false and if not set to true, broadcast datagrams won't be sent even if you send to a broadcast address.

Related

How to send packet message for specific NIC in c#

I'm a beginner with Socket programming in c# and I wonder how to send packet data for specific NIC.
I knew there was a way to set specific network device using setsockopt in python3 like that
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, 25, str(str(netinterface) + '\0').encode('UTF-8')) // netinterface => 'eth1'
except OSError :
print("Failed set eth1")
there were eth0 and eth1 and I did send packet successfully to eth1.
I found a way set option to socket like this, but I dont know how to resolve NIC using this APIs.
UdpClient udpclient = new UdpClient(new IPEndPoint(IPAddress.IPv6Any, 15118));
IPAddress multicateAddress = IPAddress.Parse("FF02::1");
udpclient.JoinMulticastGroup(multicateAddress);
Socket uSocket = udpclient.Client;
uSocket.SetSocketOption() // <- How... to?
If there is tutorials or any documents, it will help me.
Please comment thx.
Whether bind your socket to a specific IP address of an interface on the NIC you're looking for or modify your OS routing table to send packets to a specific network through a specified interface.
UdpClient isn't just a socket, but anyway I don't see an issue in binding it to a specific IP. See the docs for details.

How to use TCP Client in Android without Sockets?

I have a TCP server in C# and also a TCP Client in C#, now I need a TCP Client in Android too.
All the examples i found are related to sockets, but I'm using a simple TCP Client so they don't work.
Right now my C# TCP Client is like that:
TcpClient client = new TcpClient("127.0.0.1", 1200);
NetworkStream n = client.GetStream();
Console.WriteLine("Insert name");
string name= Console.ReadLine();
byte[] message = Encoding.Unicode.GetBytes(name);
n.Write(message, 0, message.Length);
Is there a corresponding of this function in Android?
This is the actual android client i'm trying and that doesn't work
InetAddress serverAddr = InetAddress.getByName("127.0.0.1");
socket = new Socket(serverAddr, 1200);
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(str);
First, this line:
InetAddress serverAddr = InetAddress.getByName(127.0.0.1);
contains a syntax error. It should be:
InetAddress serverAddr = InetAddress.getByName("127.0.0.1");
Second, the address "127.0.0.1" refers to the "same machine" that executes the client. In the case of your C# program, the server runs on the same machine as the client, so it worked. But in the case of Android, there in no server that runs on the "same machine", which is your Android phone (event if it is emulated, 127.0.0.1 refers to the emulated Android device, not the PC that it works on). You must specify a "good" address to the Android device that refers to the machine on which the server executes.
So, the problem is not in using sockets.
You can simply connect to your server using this line, also try to disable your firewall if your server is running on your PC.
Socket server= new Socket("192.168.1.1", 4444); // Enter your PC/Server IP address in place of 192.168.1.1

IPv4 address 0.0.0.0 and IPv6 address ::0 are unspecified addresses that cannot be used as a target address

I am trying to establish a connection to any IP on that port. Originally, I had it said to 10.0.0.7, which was the IP of another computer on my network, so I could test the client/server. However, I want it to work with any computer without having to change the IP Address to 10.0.0.7 I tried changing it to IPAddress.Any, as the name made it seem like it would accept any IP. Evidently, it didn't because now I'm getting an error. I'm confused. Below is my entire main method, which is the only method so far.
TcpClient client = new TcpClient(IPAddress.Any.ToString() , 1200);
NetworkStream stream = client.GetStream();
string messageToSend;
byte[] messageBytes;
while (true)
{
try
{
Console.WriteLine("Type a message to send");
messageToSend = Console.ReadLine();
messageBytes = Encoding.Unicode.GetBytes(messageToSend);
stream.Write(messageBytes, 0, messageBytes.Length);
}
catch
{
}
Your example can't work with IpAddress.Any.
You have to provide the ip of the server.
A client has to connect to a server with a given IP address.
But a server can listen for any IpAddress.
Reference :
https://msdn.microsoft.com/fr-fr/library/system.net.ipaddress.any(v=vs.110).aspx

How to know "The DNS name of the remote host" of a computer?

I have two programs use to communicate with each other via UDP protocol (client and server), but when the client connects to the server using the method Connect (
string hostname,
int port
), Nothing happened.
This is code:
udpclient.Connect("asuspc",6500);
string duongdan = tbduongdan.Text;
Byte[] sendbyte = Encoding.ASCII.GetBytes(duongdan);
udpclient.Send(sendbyte, sendbyte.Length);
"asuspc" is name of computer that i intend to connect.
After a while to find out, I know that the hostname is "The DNS name of the remote host" rather than the name of computer, then what is "The DNS name of the remote host"?How to know "The DNS name of the remote host" of a computer?
By definition, UDP is a connection-less protocol. You do not need to connect in order to send/receive data.
Note that calling Connect() on a UdpClient object does nothing other than setting a default remote host so that you won't have to specify it each time you use the Send method. So don't expect anything to "happen" after the client calls the Connect method.
With that out of the way, if both your server and your client are on your private LAN, why don't you use the computer's IP? e.g.
// replace 192.168.1.44 with the server's private IP
udpclient.Connect("192.168.1.44",6500);
string duongdan = tbduongdan.Text;
Byte[] sendbyte = Encoding.ASCII.GetBytes(duongdan);
udpclient.Send(sendbyte, sendbyte.Length);
Uhm... I think that a bit of TCP/IP reading will help you a lot :-)
Every machine has an assigned IP address. To not have to remember those long IP addresses, DNS servers were created, so you can write "host.domain.com", and your DNS servers tells you that this "machine DNS name" corresponds with the IP address xx.xx.xx.xx.
Said that, to know the "DNS name" of a machine, under windows (and linux) you can write:
nslookup ip_address_of_the_machine
Example: nslookup 192.168.1.2
Hope that helps.
In server side, (code to get ip address only)
// get the ip and port number where the client will be listening on
static IPEndPoint GetClientInfo()
{
// wait for client to send data
using (UdpClient listener = new UdpClient(6500))
{
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, 6500);
byte[] receive_byte_array = listener.Receive(ref groupEP);
return groupEP;
}
}
Then to get IP
var ip = clientInfo.Address.ToString();
var port = clientInfo.Port;
UdpClient client = new UdpClient(new IPEndPoint( IPAddress.Any, 6500));
client.Connect(ip, port); // use ip address
Then in client side you can recieve the data using the buffer

UDP broadcast send from PHP and receive in C#

I'm trying to send a broadcast UDP message to a C# application. I have tried the following code to send the message. Which I found on the php.net website as a comment to the socket_sendto manual page.
<?php
$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_set_option($sock, SOL_SOCKET, SO_BROADCAST, 1);
socket_sendto($sock, $broadcast_string, strlen($broadcast_string), 0, '255.255.255.255', $port);
?>
This doesn't work for me, maybe it's my network.
But it does work if I replace the broadcast IP '255.255.255.255' to my specific IP e.g. '192.168.1.128'. I can see this message coming in with Wireshark, while I can't see this using the above code. This leads me to believe there is something wrong with the PHP side of the code. I really want to use broadcasting or some kind of multicasting for my program, so I'm a bit stuck at the moment ;)
I use the following on the (C#) receiving end (for testing):
UdpClient subscriber = new UdpClient(15000);
IPEndPoint ep = new IPEndPoint(IPAddress.Any, 15000); ;
byte[] pdata = subscriber.Receive(ref ep);
string data = Encoding.ASCII.GetString(pdata);
MessageBox.Show(data);
subscriber.Close();
Any idea what could be the cause of this?
Try specifying the MSG_DONTROUTE flag in your script. Taking inspiration from this CodeGuru post, if this isn't specified the routers make the decision on whether or not to broadcast your message.
socket_sendto($sock, $broadcast_string, strlen($broadcast_string), MSG_DONTROUTE, '255.255.255.255', $port);
255.255.255.255 is a "limited" broadcast whereas your 192.168.1.255 is a "directed" broadcast.
Limited in simple terms means that it is only send within the LAN. LAN as defined by directly connected hosts, i.e. with no router in between. Routers--with a few exceptions--do not pass a limited broadcast but a directed broadcast.
Now, with your initial problem and question, I can only guess that you are sending your broadcast across a router.

Categories

Resources