c# send udp and get response - c#

I'm trying to create a little program in c# to deal with the xiaomi smart home api.
Api translation
I'm stuck at the beginning. I don't achieve to send {"cmd" : "get_id_list"} to the gateway and receive the response.
I'm trying to use this code to send but I've got nothong in response :
string i = "{\"cmd\" : \"get_id_list\"}";
UdpClient client = new UdpClient();
IPEndPoint ep = new IPEndPoint(IPAddress.Parse("192.168.1.112"), 9898);
Byte[] buffer = null;
buffer = Encoding.Unicode.GetBytes(i.ToString());
client.Send(buffer, buffer.Length, ep);
byte[] b2 = client.Receive(ref ep);
string str2 = System.Text.Encoding.ASCII.GetString(b2, 0, b2.Length);
192.168.1.112 is my gateway ip adress.
Here a screenshot of packet senders software on windows : Screenshot
We can see that the gateway reply to me the right informations.
So how to get this reply whatever the response port ?
thank for your help

As #jdweng suggests, you need to use a Connect() method on your UDP client, or it won't listen for responses. You can either do this, or use two separate UdpClients, one to send and one to receive.
string i = "{\"cmd\" : \"get_id_list\"}";
UdpClient client = new UdpClient();
client.Connect(new IPEndPoint(IPAddress.Parse("192.168.1.112"), 9898));
Byte[] buffer = null;
buffer = Encoding.Unicode.GetBytes(i.ToString());
client.Send(buffer, buffer.Length, ep);
byte[] b2 = client.Receive(ref ep);
string str2 = System.Text.Encoding.ASCII.GetString(b2, 0, b2.Length);

Related

What sort of message does Snapd's API expect?

Snapd has documentation on a REST API.
I'm able to connect to the socket from C# using the following
var snapSocket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);
var snapEndpoint = new UnixEndPoint("/run/snapd.socket");
snapSocket.Connect(snapEndpoint);
var req = Encoding.ASCII.GetBytes("GET /v2/system-info HTTP/1.1");
snapSocket.Send(req, req.Length, 0);
var bytesReceived = new byte[256];
var bytes = 0;
var response = "";
do
{
bytes = snapSocket.Receive(bytesReceived, bytesReceived.Length, 0);
response = response + Encoding.ASCII.GetString(bytesReceived, 0, bytes);
} while (bytes > 0);
Console.WriteLine(response);
But everything halts at snapSocket.Receive - a response is never sent. I suspect that there's something wrong with the message that I'm sending it.
It turns out that it expects a standard HTTP request, which means a Host: line, a Connection: Close line, and two \ns at the very end are required.
The documentation's following claim...
While it is expected to allow clients to connect using HTTPS over a TCP socket, at this point only a UNIX socket is supported.
... is meant only to imply that HTTPS and TCP do not work yet - HTTP is currently the valid request format even when using the UNIX Socket.
I am not fluent in C# at all, but maybe this python snippet can help lead into a solution:
import requests_unixsocket
session = requests_unixsocket.Session()
r = session.get('http+unix://%2Frun%2Fsnapd.socket/v2/snaps')
r.raise_for_status()
r.json()

Send packet from server to a specific client using TCP c#

I am currently writing a client-server application. The client sends a UDP broadcast message out trying to locate a server, the server sends a UDP broadcast message out identifying its location.
When a client receives a message identifying the servers location it attempts to connect to the server using socket.Connect(remoteEndPoint).
The server listens for these TCP requests on a listening socket and accepts the requests using listensocket.accept(). The clients details get stored in array (including their IP and port number)
The client sends a message to the server with information about the username and password the user entered.
The server checks the database for the username and password and depending on the result sends back a TCP message (this is where it breaks) to the client who sent the request to check the U&P using the listening socket. I am trying to use the below code to send the TCP message but it will not work as i get an error.
TCPSocket.SendTo(message, clientsArray[i].theirSocket.RemoteEndPoint);
I'm not sure about what method you are using.
But in C# there are 2 common classes that can use as server : TcpClient & Socket
in TcpClient
...
//Start Server
Int32 port = 13000;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
server = new TcpListener(localAddr, port);
server.Start();
//Accept Client
TcpClient client = server.AcceptTcpClient();
NetworkStream stream = client.GetStream();
String data = "Message From Server";
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
//Send to Client
stream.Write(msg, 0, msg.Length);
...
and in Socket using TCP
...
//Start Server
Socket listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress hostIP = (Dns.Resolve(IPAddress.Any.ToString())).AddressList[0];
IPEndPoint ep = new IPEndPoint(hostIP, port);
listenSocket.Bind(ep);
listenSocket.Listen(backlog);
//Accept Client
Socket handler = listener.Accept();
String data = "Message From Server";
byte[] msg = Encoding.ASCII.GetBytes(data);
//Send to Client
handler.Send(msg);
...
and in Socket using UDP
You shouldn't use this on your server since you are using TCP
...
IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName());
IPEndPoint endPoint = new IPEndPoint(hostEntry.AddressList[0], 11000);
Socket s = new Socket(endPoint.Address.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
String data = "Message From Server";
byte[] msg = Encoding.ASCII.GetBytes(data);
//Send to Client by UDP
s.SendTo(msg, endPoint);
...
Normally, when you get a connection from a client, you'll get a TcpClient. That class has a method GetStream(). If you like to send some data to that client, simply write your desired data to that stream.

How to send messages from server to a specific client

I am using WebSockets and trying to set up a code base for my server-client. I know how to send messages from client to server and I also know how to listen those messages from the server side.
However, how can I send a message back to a client ?
// here is the _clientSocket that I accepted
_clientSocket = _serverSocket.Accept();
int received = _clientSocket.Receive(_buffer, 0, _buffer.Length,
SocketFlags.None);
// here is the message I got from the client
string receivedMsg = Encoding.ASCII.GetString(_buffer);
if (receivedMsg == "1")
//TO DO: send back to client "This is a test message from server".
Basically you have to use the SendAsync method:
var sendbuffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes("Whatever text you want to send"));
await socket.SendAsync(sendbuffer , WebSocketMessageType.Text, true, CancellationToken.None)
.ConfigureAwait(false);
Take a look at this example: https://stackoverflow.com/a/26274839/307976
You have to call:
_clientsocket.Send(...);

UdpClient.Receive(...) doesn't receive any data

I have a socket server (written on C++) which receives requests from clients and sends responses back. So, my test client application (C#) is very simple:
try {
UdpClient udpClient = new UdpClient(10241);
// Connect
udpClient.Connect(server_ip_address, 10240);
// prepare the packet to send
iWritableBuff wbuff = new iWritableBuff();
[ ... ]
// Send
udpClient.Send(wbuff.GetBuff(), (int)wbuff.Written());
// Receive a response
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
Console.WriteLine("We've got some data from the server!!! " + receiveBytes.Length + " bytes.");
udpClient.Close();
} catch (Exception e) {
Console.WriteLine("ERROR: " + e.ToString());
}
I run both applications on the same computer. Server receives a request to port 10240 from the client port 10241 and sends a response back to client port 10241, but client never receive it. So, I'm sure that server sends packet back, because everything works perfectly with C++ client. It means that I'm, doing something wrong on my C# client. Any idea?
Thanks!
P.S.> Just test it with Berkley Socket C# client:
try {
// Create socket
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
// Bind
IPEndPoint myEP = new IPEndPoint(IPAddress.Any, 0);
s.Bind(myEP);
// prepare the packet to send
iWritableBuff wbuff = new iWritableBuff();
[ ... ]
// Send it
IPEndPoint sEP = new IPEndPoint(IPAddress.Parse(server_ip_address), 10240);
int res = s.SendTo(wbuff.GetBuff(), (int)wbuff.Written(), 0, sEP);
// Receive the response
byte[] receiveBytes = new Byte[1024];
EndPoint recEP = new IPEndPoint(IPAddress.Any, 0);
res = s.ReceiveFrom(receiveBytes, ref recEP);
Console.WriteLine("We've got some data from the server!!! " + res + " bytes.");
} catch (Exception e) {
Console.WriteLine("ERROR: " + e.ToString());
}
And it works perfect! What's is wrong with UdpSocket?
Not sure if this applies to UDPClients that don't broadcast packets but simply send one to a specified address, but I ran into a similar roadblock.
I had a UDPClient that broadcasted a udp packet for discovery of some custom machines on our network. When I tried to receive the message that the servers would simply echo back, it would not receive the information and would timeout. Turns out that if you use a UDPClient that broadcasts a message out, it WILL NOT be able to receive messages back. It's not documented anywhere, except for one forum topic on msdn that I luckily came across.
The solution was to send the message, immediately close the socket, open a NEW UDPClient on the same port, then use this new UDPClient to receive the echoed back UDP packet. Very annoying.
Give that a shot and see if it works. It definitely works for sending out a broadcasted packet.

Problem in Sending messages from Server to Client

im making a Window Application in C# using Socket Programming. I have developed a Server & a Client. Both are working fine but the problem which im gettin is that when ever i send any message from CLIENT, its send perfectly and receives on SERVER but whenever i try to send any message from SERVER it doesn't send to Client, since at the beginning when a connection is built, server sends the message to client that "Connection Established" and received at Client perfectly,but later on server does not send any message to client!!! Could anyone please help me out ???????
Regards
Umair
EDIT:
//Code at SERVER for SENDING...
private void button_send(object sender, EventArgs e)
{
string input = textBoxWrite.Text;
byte[] SendData = new byte[1024];
ASCIIEncoding encoding = new ASCIIEncoding();
SendData = encoding.GetBytes(input);
client.Send(SendData,SendData.Length,SocketFlags.None);
textBoxShow.Text = "Server: " + input;
}
//Code at CLIENT for receiving
NetworkStream networkStream = new NetworkStream(server);
string input = textBoxUser.Text + ": " + textBoxWrite.Text;
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] inputByte = encoding.GetBytes(input);
if (networkStream.CanWrite)
{
networkStream.Write(inputByte, 0, inputByte.Length);
textBoxShow.Text = textBoxShow.Text + Environment.NewLine + input;
textBoxWrite.Text = "";
networkStream.Flush();
}
I'm not sure how best to help based on the information you've provided, but perhaps you could look at something like this example of C# socket programming and compare with your own application.

Categories

Resources