Cannot send data over UDP in UWP - c#

I am trying to send the data over UDP in UWP Application. However, I cannot see the data being sent on Wireshark.
Just to check if firewall is causing any issue, I disabled it and tried sending the data again. However, I still don't see the data on Wireshark. Here's my code:
UdpClient client = new UdpClient();
client.EnableBroadcast = true;
client.Connect(IPAddress.Broadcast, 9520);
Byte[] senddata = Encoding.ASCII.GetBytes("Hello!");
client.Send(senddata, senddata.Length);
client.Close();
Am I missing something obvious here? I am using Visual Studio 2017 to build this UWP Application.

This page explains why the above code will not work if the App capabilities were not configured.
I didn't configure the capabilities before asking this question. However, I came across the page and enabled some capabilities (Internet(Client & Server), Internet(Client), Private Networks(Client & Server)).
After configuring them, my earlier code is working fine.
If you're facing the same problem, please configure the capabilities by going to Package.appxmanifest -> Capabilities and then rebuild the solution. After correctly enabling the capabilities, your app shall send the data. :) :)

You can use codes below I write and test it, it works fine
byte[] package= Encoding.ASCII.GetBytes(udpInfo[2].ToString());
IPEndPoint ep = new IPEndPoint(IPAddress.Parse(udpInfo[0].ToString()), Convert.ToInt32(udpInfo[1]));
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
try
{
sock.SendTo(package, ep); //send packet to sw ip
Console.WriteLine("package sent");
return true;
}
catch (Exception ex)
{
Console.WriteLine("package can't sent");
return false;
}
EDIT: udpInfo arraylist declaration below:
public ArrayList udpInfo = new ArrayList(); // 0-ip 1-port 2-command
udpInfo[0] = "192.168.1.1"
udpInfo[1] = 1111
udpInfo[2] = "some commands"

Related

Can I force my web socket not to use SSL even though my site is served under SSL?

I have a JavaScript client.
I have a web socket and it is trying to talk to my server.
My web app runs under https and I have used Open SSL for get my certificates.
In my C# I am using the Socket object to receive client requests.
My clients can connect but the when I try to read/parse the headers it is encrypted. (I do not know how to decrypt).
If occured to me if my web socket did not use SSL the problem would go away. But, even if I set the uri in my client to:
var url = "ws://192.168.0.9:8090/Relayer";
It is changed to:
var url = "wss://192.168.0.9:8090/Relayer";
This is my server code:
//server starting to listen
serverSocket = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP );
serverSocket.Bind( new IPEndPoint( IPAddress.Any, 8090 ) );
serverSocket.Listen( 128 );
serverSocket.BeginAccept( null, 0, OnAccept, null );
//server responding to Client Request:
private static Socket serverSocket;
private static void OnAccept(IAsyncResult result)
{
byte[] buffer = new byte[1024];
try
{
Socket client = null;
string headerResponse = "";
if (serverSocket != null && serverSocket.IsBound)
{
client = serverSocket.EndAccept(result);
var i = client.Receive(buffer);
//my many attempts to read the data....
string unicode = (Encoding.UTF8.GetString(buffer)).Substring(0, i);
string str = Uri.UnescapeDataString(unicode);
var outputs = System.Net.WebUtility.HtmlDecode(unicode);
}
if (client != null)
{
/* Handshaking and managing ClientSocket */
}
}
catch (SocketException ex)
{
Logger.LogVerbose(LoggerNames.Error, ex.ToString());
}
finally
{
if (serverSocket != null && serverSocket.IsBound)
{
serverSocket.BeginAccept(null, 0, OnAccept, null);
}
}
}
So, can I FORCE my web socket not to use SSL?
Thanks
OKAY
After reading stuff I understand it is not a good idea to mix http and https and ws and wss.
Any ideas to get this working using SSL/wss then that would be good :)
Can I force my web socket not to use SSL even though my site is served under SSL?
If your JavaScrip client follows security conventions, then the answer is no. The answer is also "it shouldn't".
There are a number of reasons for this, but the following reason is quite enough:
When a user observes that the website is encrypted, they assume that any private information they share will not be visible to third parties. This is part of the promise made by encryption. However, by allowing clear-text (unencrypted) communication after stating the site is encrypted, this promise could be broken.
This is why secure clients will not allow non-encrypted communication (i.e., WebSockets, XHR, etc') within a secure website.
My clients can connect but the when I try to read/parse the headers it is encrypted. (I do not know how to decrypt).
The encrypted data should be passed through the SSL layer to be decrypted.
Often, many languages will provide an "SSL Socket" abstraction that behaves like a socket but automatically encrypts / decrypts data.
As mentioned in the comments the SslStream might be what you're looking for (see Jesse de Wit's comment).

How to open a localhost server accessible from all devices in C# Windows Forms

I'm building a C# (Windows Forms) application that should open a local server on the network. I've searched and googled thoroughly but it seems that nobody was exposed to the same problem that I have.
The code I'm posting below does indeed open up a localhost in the given port (when ran through VS or as a normal build), but the problem is, it's only accessible through my laptop. If I go to the IP address and port through my phone or any another laptop, it doesn't even find the server. After several tries and brainstorming. It seems to me that it doesn't really open up the server on the network per se. It just creates some sort of a virtual localhost accessible to and through the machine which ran the code only.
This is my code:
private HttpListener Listener = null;
//CHECK IF HTTP IS SUPPORTED
try
{
Listener = new HttpListener();
Listener.Prefixes.Add("http://localhost:3000/");
Listener.Start();
Listener.BeginGetContext(GetContextCallback, null);
}
catch {} //SUPPRESS THE EXCEPTION/ERROR
private void GetContextCallback(IAsyncResult ar)
{
// Get the context
var context = Listener.EndGetContext(ar);
// listen for the next request
Listener.BeginGetContext(GetContextCallback, null);
var responseString = string.Format("Hello, this is a template text");
byte[] buffer = Encoding.UTF8.GetBytes(responseString);
// and send it
var response = context.Response;
response.ContentType = "text/html";
response.ContentLength64 = buffer.Length;
response.StatusCode = 200;
response.OutputStream.Write(buffer, 0, buffer.Length);
response.OutputStream.Close();
}
I'm not unfamiliar with either the concept or C# itself. I've built several applications that do the same with Node.js and have built a handful of apps in C#. But this is my first try writing such an application in C#. What am I missing?

Multiple Clients on TCPListener C# / Server sending Data [duplicate]

This question already has an answer here:
C# TcpClient: Send serialized objects using separators?
(1 answer)
Closed 4 years ago.
Being a "novice" in C# and C# Network programming I tried to make a simple chat in C# using TCPClient and TCPListener , I've managed to send data from client to server but if I add a second client the server doesnt read his data and i have a second issue I couldn't figure out how to send data from server to client using TCPListener .
Server :
while (true)
{
Socket client = Server.AcceptSocket();
Console.WriteLine("Connection accepted from " + client.RemoteEndPoint);
count += 1;
string msg;
byte[] buf = new byte[1024];
client.Receive(buf);
msg = Encoding.UTF8.GetString(buf);
Console.WriteLine("Received... " + msg + "");
}
}
Client :
while (true)
{
Console.WriteLine("Connected");
Console.Write("Enter the string to be transmitted : ");
String msg = Console.ReadLine();
Stream stm = tcpClient.GetStream();
ASCIIEncoding asen= new ASCIIEncoding();
byte[] send = asen.GetBytes(msg);
Console.WriteLine("Transmitting.....");
stm.Write(send, 0, send.Length);
if (msg == "/Q"){
tcpClient.Close();
Environment.Exit(0);
}
}
If you see any absurdity / Mistake in my code please tell me i'm here to learn !
Thank You
Where I am not the best with C# this post Server Client send/receive simple text how to create C# simple server, and should fix the first issue of the client not being able to recive data from the server.
As for the second issue not being able to support mulitple connections, this could be to do with there is no threading, so the question is do you want to create a C# webserver or a C# application which utilizes TCP communication to a server.
if the answer is the latter, then I would look to installing tried and tested server such a Apache or Nginx. this will allow the server to handle multiple requests on your behalf and skip having to handle multiple connections and threads, while you are learning more about the client server relationship. also this article may help setting up the fastcgi environment for the appliction http://www.mono-project.com/docs/web/fastcgi/nginx/
otherwise then you will have to look at how to handle multiple clients which this post looks like it could help TCP server with multiple Clients

Using specific network interface in C# with VLC ActiveX Plugin

I'm working now on the IPTV program in C#. As a media engine I'm using a VLC ActiveX Plugin. Data goes over UDP protocol.
Now I ran into the problem.
I have several networking interfaces. For example, I have Local Area Connection, that is used for network and Internet access, and VirtualBox Network.
First connection has an IP-address of 10.10.10.2 and second - 192.168.1.2.
When I trying to join multicast-group, some of IGMP-queries go through the VirtualBox Network instead of Local Area Connection. So I don't receive a multicast-traffic.
I need to choose specific interface (Local Area Network) for my application. So all data will going through this network interface.
I found some answers in the Internet, but not specifically for my problem.
Here's something, that I was trying to use:
IPAddress localAddress = IPAddress.Parse("10.10.10.2");
IPEndPoint localEndPoint = new IPEndPoint(localAddress, 0);
Socket client = new Socket(localEndPoint.AddressFamily, SocketType.Raw, ProtocolType.Igmp);
client.Bind(localEndPoint);
axVLCPlugin21.playlist.add("udp://#239.1.9.2:1234", axVLCPlugin21, null);
axVLCPlugin21.playlist.play();
But it's not working. Can someone help me, please?
Thank you!
I finally did it! I make a socket and bind it using my needed network interface. After that, I send IGMP-query using this socket and then receive data over needed network interface.
Now I'm using this code:
Socket mcastSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPAddress localAddress = IPAddress.Parse("10.10.10.2");
IPEndPoint localEndPoint = new IPEndPoint(localAddress, 0);
mcastSocket.Bind(localEndPoint);
IPAddress mcastAddress = IPAddress.Parse("239.1.9.2");
MulticastOption mcastOption = new MulticastOption(mcastAddress, localAddress);
mcastSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, mcastOption);
axVLCPlugin21.playlist.add("udp://#239.1.9.2:1234", axVLCPlugin21, null);
axVLCPlugin21.playlist.play();

Socket communication for inter-WebRole communications in Azure

I'm trying to make a simple client-server in Azure. I have the client in one webrole and the server in another, and both belong to the same tenant.
I want to use simple socket communication between the two to send a dummy file from client to server.
Here is how I wrote my app (some code removed for clarity):
1- Define "internal" tcp endpoints for each role. Assume server's port is 9000. Client's port is 9010.
2- The client sends a dummy file to the server as follows:
byte[] buffer = File.ReadAllBytes(filePath);
mSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
mSocket.Connect(IPAddress.Parse(serverIPString), 9000);
mSocket.Send(buffer);
3- On the server, I do the following:
IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 9000);
mSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
mSocket.Bind(ipEnd);
mSocket.Listen(BACKLOG);
Socket socket = mSocket.Accept();
byte[] buffer = new byte[BUFFER_SIZE];
int byteCount = socket.Receive(buffer);
Everything works fine locally in the Azure emulator, but when I go to the cloud the server doesn't get any connections :(
Please help!
Addendum:
Someone asked how I find my endpoints.
I display my endpoints on the main page of the server as follows and let the sender/client specify the IP they want to send the file to in a textbox.
foreach (var instance in RoleEnvironment.CurrentRoleInstance.Role.Instances)
foreach (KeyValuePair<string, RoleInstanceEndpoint> pair in instance.InstanceEndpoints)
addresses += "[" + pair.Key + "] " + pair.Value.IPEndpoint.Address + ":" + pair.Value.IPEndpoint.Port + ", ";
This might be a network/IP issue like a firewall or the code not recognizing the IPs and not letting communication through.
Your server needs to be in a loop waiting for a connection. I'm not sure if you just summarized that out for your sample code, or if that is what is missing. Your use of the Socket interface looks correct as far as the order in which you are invoking its operations.
Hope this helps http://msdn.microsoft.com/en-us/library/6y0e13d3.aspx
Addendum: Nevermind, just noticed Socket.Accept() suspends so shouldn't have the problem I was thinking of when I looked at it.

Categories

Resources