I have written a SNTP Client code to retrieve time information as below. In this, the code stops at line
_sntpMessageRequest.SNTPData = _udpClient.Receive(ref _ipEndpoint);
as SNTP Server is not responding.
public bool QueryTimeSynchronizationServer()
{
UdpClient _udpClient = null;
IPEndPoint _ipEndpoint = null;
string _ipString = null;
IPAddress _ipAddress = null;
int _portNumber = 123;
try
{
//Valid Ip Address
_ipString = "ip address";
IPAddress.TryParse(_ipString, out _ipAddress);
_ipEndpoint = new IPEndPoint(_ipAddress, _portNumber);
//SNTPMessageRequest-> a object holds the Byte array for SNTP request and do other supporting functions
SNTPMessageRequest _sntpMessageRequest = FrameSNTPMessageRequest();
using (_udpClient = new UdpClient(123))
{
_udpClient.Client.SendTimeout = 5000;
_udpClient.Client.ReceiveTimeout = 5000;
_udpClient.Connect(_ipEndpoint);
_udpClient.Send(_sntpMessageRequest.SNTPData, _sntpMessageRequest.SNTPData.Length);
//Code stops at below line as SNTP Server is not responding.
_sntpMessageRequest.SNTPData = _udpClient.Receive(ref _ipEndpoint);
_sntpMessageRequest.ReceptionTimestamp = DateTime.Now;
string _serverTime = _sntpMessageRequest.TransmitTimeStamp.ToString();
}
}
catch (Exception ex)
{
}
return true;
}
private SNTPMessageRequest FrameSNTPMessageRequest()
{
SNTPMessageRequest _sntpMessageRequest = new SNTPMessageRequest();
_sntpMessageRequest.VersionNumber = VersionNumber.Version3;
_sntpMessageRequest.Mode = Mode.Client;
for (int i = 1; i < 48; i++)
{
_sntpMessageRequest.SNTPData[i] = 0;
}
_sntpMessageRequest.TransmitTimeStamp = DateTime.Now.ToLocalTime();
return _sntpMessageRequest;
}
Kindly help me with where i am doing mistake.
Related
I am having problems updating a ListView on C# WinForm. The application is a test harness which connects to a TCP Server and receives a data stream. The test harness will then be used to create multiple connections to the server to do load testing. Each task is started using the following command where the number of task is entered on the form:
for (int i = 0; i < noTasks; i++)
{
bool saveAudio = noTasksCheckedListBox.GetItemCheckState(i) == CheckState.Checked; // true : false;
taskArray[i] = Task.Run(() => SendMessage((initId + i).ToString(), saveAudio, audioServerIP));
}
The SendMessage function creates the TCP client connection and creates a AsyncCallBack to process the incoming stream.
void SendMessage(string id, bool saveWav, string serverIP)
{
TcpClient tcpclientAudio = new TcpClient();
string message = "GET /msg?id=" + id + "&type=0 HTTP/1.1\r\n";
NetworkObject audioObj = new NetworkObject
{
tcp = tcpclientAudio,
ConnectionType = FileType.Audio,
URL = message
};
if (saveWav)
{
tcpclientAudio.BeginConnect(IPAddress.Parse(serverIP), 8008, new AsyncCallback(CallBackConnectMethod01), audioObj);
}
else
{
tcpclientAudio.BeginConnect(IPAddress.Parse(serverIP), 8008, new AsyncCallback(CallBackConnectMethod02), audioObj);
}
}
The only difference between the CallBackConnctMethod is that 02 save the data to a file.
void CallBackConnectMethod02(IAsyncResult result)
{
NetworkObject obj = (NetworkObject)result.AsyncState;
TcpClient tcp = obj.tcp;
NetworkStream ns = tcp.GetStream();
startedProcessCount++;
int thisTask = startedProcessCount;
byte[] buffer = new byte[2048];
string message = obj.URL;
byte[] request = Encoding.ASCII.GetBytes(message);
ns.Write(request, 0, request.Length);
ns.Read(buffer, 0, 1000);
RefreshTable(thisTask, "Incoming", null);
......
}
When debugging the app goes to the RefreshTable function a disappears when it goes in to the delegate section.
private void RefreshTable(int taskNo, string status, string misc)
{
if (this.tasksListView.InvokeRequired)
{
this.Invoke((MethodInvoker) delegate {
DateTime nowDateTime = DateTime.Now;
string now = nowDateTime.Year.ToString("D4") + nowDateTime.Month.ToString("D2") + nowDateTime.Day.ToString("D2") + "-" + nowDateTime.Hour.ToString("D2") + nowDateTime.Minute.ToString("D2") + nowDateTime.Second.ToString("D2");
string taskId = "Task-" + taskNo.ToString("D3");
if (status == "Incoming")
{
ListViewItem taskLVI = tasksListView.Items.Add(taskId);
taskLVI.SubItems.Add(now);
taskLVI.SubItems.Add(" ");
taskLVI.SubItems.Add(" ");
if (string.IsNullOrEmpty(misc))
taskLVI.SubItems.Add(" ");
else
taskLVI.SubItems.Add(misc);
taskLVI.SubItems.Add(" ");
}
else
{
switch (status)
{
case "Lost":
case "Completed":
case "Exception":
ListViewItem listViewItem = null;
for (int i = 0; i < tasksListView.Items.Count; i++)
{
if (tasksListView.Items[i].SubItems[0].Text == taskId)
{
listViewItem = tasksListView.Items[i];
break;
}
}
if (listViewItem != null)
ToListViewItem(listViewItem, status, misc, now);
break;
default:
break;
}
}
tasksListView.Refresh();
});
}
}
I am writing a messaging application using C# and unity for my a level project, it is using a tcp client-sever model. I have created a list of sockets that can receive messages, but I have to specify the socket to receive the message from, this is fine for testing when i only have 1 client, but I need to be able to handle more connections, and looping through each socket to try and receive a message from it seems very inefficient and slow.
My question is: how can I receive messages from multiple clients without using the aforementioned method?
I'm going to post the specific sections, and then the entire code so you understand what I'm doing.
This is the thread that deals with receiving the data form the socket
public static void Thread1()
{
for (int i = 0; i <= 2; i++)
{
byte[] b = new byte[155];
///////// I need to specify the socket to receive from////////
int k = counter.numbers1[counter.i2].Receive(b);
//////////////////////////////////////////////////////////////
string k1 = "";
for (int i3 = 0; i3 < k; i3++)
k1 = k1 + Convert.ToChar(b[i3]);
Console.WriteLine(k1);
string sender_endpoint = k1.Substring(0, 21); ;
string receiver_endpoint = k1.Substring(22, 21);
string message = k1.Substring(44, 100);
string msgtype = k1.Substring(145, 1);
Console.WriteLine(k1.Length);
Console.WriteLine(sender_endpoint);
Console.WriteLine(receiver_endpoint);
Console.WriteLine(message);
Console.WriteLine(msgtype);
if (msgtype == "0") //message
{
Console.WriteLine("000");
}
else if (msgtype == "1") //command
{
Console.WriteLine("111");
}
}
}
The full server code is:
namespace server
{
static class counter
{
public static int i2 = 0;//main listener
public static int i4 = 0;//port number
public static List<TcpListener> numbers = new List<TcpListener>();//listeners
public static List<Socket> numbers1 = new List<Socket>();//sockets
}
class server_code
{
public static void Main()
{
string xyz123 = "x";
Thread thread3 = new Thread(new ThreadStart(Thread3));
Thread test_thread = new Thread(() => Test_Thread (xyz123));
thread3.Start();
}
public static void Thread1()
{
//message reactions
for (int i = 0; i <= 2; i++)
{
byte[] b = new byte[155];
int k = counter.numbers1[counter.i2].Receive(b);
string k1 = "";
for (int i3 = 0; i3 < k; i3++)
k1 = k1 + Convert.ToChar(b[i3]);
Console.WriteLine(k1);
string sender_endpoint = k1.Substring(0, 21); ;
string receiver_endpoint = k1.Substring(22, 21);
string message = k1.Substring(44, 100);
string msgtype = k1.Substring(145, 1);
Console.WriteLine(k1.Length);
Console.WriteLine(sender_endpoint);
Console.WriteLine(receiver_endpoint);
Console.WriteLine(message);
Console.WriteLine(msgtype);
if (msgtype == "0") //message
{
Console.WriteLine("000");
}
else if (msgtype == "1") //command
{
Console.WriteLine("111");
}
}
}
public static void Thread2()
{
//client message receiver
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
IPAddress ipAd = IPAddress.Parse(ip.ToString());
counter.numbers.Add(null);
counter.numbers1.Add(null);
Console.WriteLine("");
Socket xyz1 = counter.numbers[counter.i2].AcceptSocket();
counter.numbers1[counter.i2] = xyz1;
ASCIIEncoding asen = new ASCIIEncoding();
counter.numbers1[counter.i2].Send(asen.GetBytes(counter.numbers1[counter.i2].RemoteEndPoint.ToString()));
Console.WriteLine("Connection accepted from " + counter.numbers1[counter.i2].RemoteEndPoint);
Console.WriteLine("connecting to " + counter.numbers[counter.i2].LocalEndpoint);
//System.Threading.Thread.Sleep(3000);
Thread thread1 = new Thread(new ThreadStart(Thread1));
thread1.Start();
}
}
}
public static void Thread3()
{
//new clients acception
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
for (int i = 0; i <= 10; i++)
{
Console.WriteLine(ip.ToString());
IPAddress ipAd = IPAddress.Parse(ip.ToString());
TcpListener myList = new TcpListener(ipAd, 8080);
myList.Start();
Console.WriteLine("The local endpoint is :" + myList.LocalEndpoint);
Socket s = myList.AcceptSocket();//////////////////////////////////////////////
Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
Console.WriteLine("connecting to " + myList.LocalEndpoint);
ASCIIEncoding asen = new ASCIIEncoding();
counter.i2 = counter.i2 + i;
int portno = 8000;
s.Send(asen.GetBytes(portno.ToString()));
Console.WriteLine();
myList.Stop();
s.Close();
Thread thread2 = new Thread(new ThreadStart(Thread2));
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
counter.numbers.Add(null);
TcpListener xyz = new TcpListener(ipAd, portno);
counter.numbers[counter.i2] = xyz;
//Console.WriteLine(counter.i4);//current portno
counter.numbers[counter.i2].Start();
Console.WriteLine("The local End point is :" + counter.numbers[counter.i2].LocalEndpoint);
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
thread2.Start();
}
}
}
}
}
The full client code is:
public class cc : MonoBehaviour
{
public InputField NameField;
private string x;
private string y = "";
//private int z = 0;
static class ipadressnumber{
public static string ipadressno = "192.168.1.250";
}
public void Start(){
TcpClient tcpclnt = new TcpClient();
tcpclnt.Connect(ipadressnumber.ipadressno,8080);
Stream stm = tcpclnt.GetStream();
byte[] bb=new byte[100];
int k=stm.Read(bb,0,100);
for (int i=0;i<k;i++){
y = y + Convert.ToChar(bb[i]);
}
//Debug.Log(y);
tcpclnt.Close();
}
public void OnSubmit()
{
x = NameField.text;
//Debug.Log(x);
try
{
System.Net.IPAddress ipad = IPAddress.Parse(ipadressnumber.ipadressno);
IPEndPoint ipLocalEndPoint = new IPEndPoint(ipad,8888);
//TcpClient clientSocket = new TcpClient(ipLocalEndPoint);
TcpClient tcpclnt1 = new TcpClient();
//Debug.Log(y);
tcpclnt1.Connect(ipadressnumber.ipadressno,int.Parse(y));
Stream stm = tcpclnt1.GetStream();
byte[] bb=new byte[100];
int k=stm.Read(bb,0,100);
string lclep = "";
for (int i=0;i<k;i++)
{
lclep = lclep + Convert.ToChar(bb[i]);
}
String str=x;
////////////format of message:(sender endpoint, recipient endpoint, message, message type, check sum/digit)
string message = "";
int strlen = 21;
int msglen = 100;
string msgtype = "0";// 0 = message, 1 = command
lclep = Convert.ToString(lclep);
Debug.Log (lclep);
while (strlen > lclep.Length)
{
Debug.Log('1');
lclep = lclep + "#";
}
string rmtep = "000.00.00.000:8000";
while (strlen > rmtep.Length)
{
Debug.Log ('2');
rmtep = rmtep + "#";
}
while (msglen > x.Length)
{
Debug.Log ('3');
x = x + "#";
}
message = message + lclep + ':' + rmtep + ':' + x + ':' + msgtype + ':';
Debug.Log(message);
ASCIIEncoding asen= new ASCIIEncoding();
byte[] ba = new byte[155];
ba=asen.GetBytes(message);
stm.Write(ba,0,ba.Length);
tcpclnt1.Close();
}
catch (Exception e) {
Console.WriteLine("Error..... " + e.StackTrace);
}
}
}
The output is this:
192.168.1.250
The local End point is :192.168.1.250:8080
Connection accepted from 192.168.1.250:54024
connecting to 192.168.1.250:8080
The local End point is :192.168.1.250:8000
192.168.1.250
The local End point is :192.168.1.250:8080
Connection accepted from 192.168.1.250:54055
connecting to 192.168.1.250:8000
192.168.1.250:54055##:000.00.00.000:8000###:message test 1 for stackoverflow####################################################################:0:
147
192.168.1.250:54055##
000.00.00.000:8000###
message test 1 for stackoverflow####################################################################
0
000
As you can see I don't get any errors so all I need is a way to receive messages form multiple clients.
It will be great to have a Minimal, Complete, and Verifiable example https://stackoverflow.com/help/mcve but I will give a possible solution to the problem I undertood: How to listen for multiple sockets and process their messages simultaneously.
You could start one thread for each socket you need, this Reader Thread would read the entire message and send to a thread safe list in another thread that I will call the Processing Thread. This last thread will apply your business logic to the data read by your socket, generate a response and send it to another thread: The Writer Thread.
Socker -> Readers -> Processor -> Writer
Don't start your threads like in your Thread3 and Thread2 methods, this demands too much CPU and can slow down your applocation. Create the threads beforehand and start then in the apropriate order.
public static bool DataCheck(string RefNo, out string region)
{
region = "";
try
{
string url = "https://plugin.comapny.com/api/DataCheck";
using (var client = new WebClient())
{
Jobvalidation JVObj = new Jobvalidation();
JVObj.RefNo = RefNo.ToUpper();
JVObj.ConnectionString = Configration.DMSConfig.Connectionstring;
JVObj.Zone = Configration.DMSConfig.ZONE;
client.Headers.Add("Content-Type:application/json");
client.Headers.Add("Accept:application/json");
string result = client.UploadString(url, JsonConvert.SerializeObject(JVObj));
JVObj = JsonConvert.DeserializeObject<Jobvalidation>(result);
region = JVObj.region;
bool flag = Convert.ToBoolean(JVObj.flag);
return flag;
}
}
catch (Exception ex)
{
//string result;
region = "Exception:" + ex.Message;
return false;
}
}
when we hit the service from local machines we are getting the above error. above is my code could you please check and help for this
I have create a DNS request using C# and PCAP. I checked the request using the wireshark. but there are not response.
I have compared DNS request which have a response. The flags and DNS query values are same.
I cant figure out why the dns resolver is not sending the response. Please help me.
Thank you.
My packet generating method:
private Packet getPacket(string s, string d,string domain)
{
Random r = new Random();
EthernetLayer ethernetLayer =
new EthernetLayer
{
Source = new MacAddress("00:0C:29:E5:FA:36"),
Destination = new MacAddress("00:0c:29:e5:fa:36"),
EtherType = EthernetType.None, // Will be filled automatically.
};
IpV4Layer ipV4Layer =
new IpV4Layer
{
Source = new IpV4Address(s),
CurrentDestination = new IpV4Address(d),
Fragmentation = IpV4Fragmentation.None,
HeaderChecksum = null, // Will be filled automatically.
Identification = 123,
Options = IpV4Options.None,
Protocol = null, // Will be filled automatically.
Ttl = 100,
TypeOfService = 0,
};
UdpLayer udpLayer =
new UdpLayer
{
SourcePort =ushort.MaxValue,
DestinationPort = 53,
Checksum = null, // Will be filled automatically.
CalculateChecksumValue = true,
};
DnsLayer dnsLayer =
new DnsLayer
{
Id = ushort.Parse(r.Next(0,99999).ToString()),
IsResponse = false,
OpCode = DnsOpCode.Query,
IsAuthoritativeAnswer = false,
IsTruncated = false,
IsRecursionDesired = true,
IsRecursionAvailable = false,
FutureUse = false,
IsAuthenticData = false,
IsCheckingDisabled = false,
ResponseCode = DnsResponseCode.NoError,
Queries = new[]
{
new DnsQueryResourceRecord(new DnsDomainName("col.stc.s-msn.com"),
DnsType.A,
DnsClass.Internet),
},
Answers = null,
Authorities = null,
Additionals = null,
DomainNameCompressionMode = DnsDomainNameCompressionMode.All,
};
PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, udpLayer, dnsLayer);
return builder.Build(DateTime.Now);
}
}
This is my packet sending function:
private static void performRequest(LivePacketDevice device)
{
using (PacketCommunicator communicator = device.Open(100,PacketDeviceOpenAttributes.Promiscuous,1000))
{
for (int i = 0; i < threadCount; i++)
{
Thread requester= new Thread(() =>
{
try
{
Program p = new Program();
Random r = new Random();
string resolve = resolvers[r.Next(0, resolvers.Count-1)].ToString();
communicator.SendPacket(p.getPacket(destinationIP.ToString(), resolve, domainName));
p = null;
r = null;
}
catch (Exception ex) { Console.WriteLine(ex.Message); }
});
requester.Start();
Thread.Sleep(1000);
}
}
}
I checked your "getPacket" method but have not found obvious problem, so I just tried it, of course, changed mac addresses and IP addresses, I did get response.
But your packet sending method seems wrong, what is the "DestinationIP", it should source IP, in other words, local IP address of the selected device.
I'm currently developing a small server/client application for a personal project. The server is meant to be run in Linux under Mono while the client is being run from a Windows PC.
I have an issue where I am passing data to the server (In this case string value of "on" and "off") however an if statement is always returning a false value.
The code from the server is as follows
public void startServer() {
TcpListener listen = new TcpListener(serverIP, 10000);
listen.Start();
Console.Clear();
Console.WriteLine("IP Address = {0}", serverIP.ToString());
Console.WriteLine("Server is listening for connection");
Socket a = listen.AcceptSocket();
Console.WriteLine("Connection from {0}", a.RemoteEndPoint);
ASCIIEncoding respond = new ASCIIEncoding();
a.Send(respond.GetBytes("You are connected to LED Control Server"));
bool keepListening = true;
while (keepListening) {
byte[] b = new byte[1000];
a.Receive(b);
Console.WriteLine("Message Received from {0}, string: {1}", a.RemoteEndPoint, recData(b));
string serverMsg = procIns(recData(b));
a.Send(respond.GetBytes(serverMsg));
}
}
private string recData(byte[] b) //receiving data from the client {
int count = b.Length;
string message = "";
for (int a = 0; a < count; a++) {
message += Convert.ToChar(b[a]);
}
return message;
}
private string procIns(string instruction) {
string returnMsg;
Console.WriteLine(instruction.ToLower());
if (instruction.ToLower() == "on") {
FileGPIO gpio = new FileGPIO();
gpio.OutputPin(FileGPIO.enumPIN.gpio17, true);
returnMsg = "GPIO 17 1";
} else if (instruction.ToLower() == "off") {
FileGPIO gpio = new FileGPIO();
gpio.OutputPin(FileGPIO.enumPIN.gpio17, false);
returnMsg = "GPIO 17 0";
} else {
returnMsg = "Invalid Command";
}
return returnMsg;
}
The cause for the if statement in procIns method returning false is escaping me, if anyone could offer any advice I would appreciate it!
I would guess it would have to be padded spaces. Try this instead...
if (instruction.Trim().ToLower() == "on")
while (keepListening) {
byte[] b = new byte[1000];
int bytesRcvd = a.Receive(b);
Console.WriteLine("Message Received from {0}, string: {1}", a.RemoteEndPoint, recData(b));
string serverMsg = procIns(recData(b, bytesRcvd ));
a.Send(respond.GetBytes(serverMsg));
}
a.Receive(b) method returns number of bytes received. You can store the value in some variable and pass the variable to recData method.
private string recData(byte[] b, int bytesRcvd) {
string message = "";
for (int a = 0; a < bytesRcvd; a++) {
message += Convert.ToChar(b[a]);
}
return message;
}
The number of bytes received will help in truncating the extra values in byte array.