I am developing a windows form application. I have a requirement, need ping the system ip address with parameters. like ping IP Address -n 1.
I am Unable to pass the parameter using ping.send function.
Any one can help me.
use Ping class. This provides a more organized approach
using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
namespace Examples.System.Net.NetworkInformation.PingTest
{
public class PingExample
{
// args[0] can be an IPaddress or host name.
public static void Main (string[] args)
{
Ping pingSender = new Ping ();
PingOptions options = new PingOptions ();
// Use the default Ttl value which is 128,
// but change the fragmentation behavior.
options.DontFragment = true;
// Create a buffer of 32 bytes of data to be transmitted.
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes (data);
int timeout = 120;
PingReply reply = pingSender.Send (args[0], timeout, buffer, options);
if (reply.Status == IPStatus.Success)
{
Console.WriteLine ("Address: {0}", reply.Address.ToString ());
Console.WriteLine ("RoundTrip time: {0}", reply.RoundtripTime);
Console.WriteLine ("Time to live: {0}", reply.Options.Ttl);
Console.WriteLine ("Don't fragment: {0}", reply.Options.DontFragment);
Console.WriteLine ("Buffer size: {0}", reply.Buffer.Length);
}
}
}
}
You can spam a cmd process and get its output.
ProcessStartInfo processInfo = new ProcessStartInfo("cmd");
processInfo.RedirectStandardInput = true;
processInfo.RedirectStandardOutput = true;
processInfo.UseShellExecute = false;
processInfo.CreateNoWindow = true;
Process process = Process.Start(processInfo);
process.StandardInput.WriteLine("ping 127.0.0.1 -n 1 -i 10");
process.StandardInput.Close();
string answer = process.StandardOutput.ReadToEnd();
process.WaitForExit();
process.Close()
Console.WriteLine(answer);
Related
I'm using NetBeans to make a web application and using pgadmin4 for my database. The problem is when I'm making a connection pool.
This is my database http://prntscr.com/hzwn9h and I think the problem is because I want something like that http://prntscr.com/hzwnj2 but I have this http://prntscr.com/hzwnrw. I have tried a lot of solutions but it doesn't work and I don't know what else I have to do. One of the things I have tried was this https://rivaso.wordpress.com/2012/02/19/how-to-setup-a-new-database-in-postgresql-and-glassfish/ but unfortunately unsuccessful
Following code snippet shows how to establish connection for PostgreSQL using jdbc driver. Make sure to add jdbc driver to libraries.
public Connection DBConnect() {
try {
String host = "localhost";//host
String port = "5432";//db port
String db = "exp";//database name
String user = "root";//database username
String pass = "1234";//password
//connection url
String url = "jdbc:postgresql://" + host + ":" + port + "/" + db;
//initialize jdbc driver for postger sql
Class.forName("org.postgresql.Driver");
Connection conn = DriverManager.getConnection(url, user, pass);
//return connection
return conn;
} catch (Exception e) {
System.out.println("Error : " + e.getMessage());
return null;
}
}
reference : jdbc.postgresql.org
public static void main (String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/yourdatabasename";
Connection conn = DriverManager.getConnection(url, user,password);
conn.close();
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
I want to send a command to my Sonos speaker. With my Windows application that is easy. I just use the TcpClient example provided on Microsoft website (shown below).
public void Connect(String server, String message)
{
try
{
TcpClient client = new TcpClient(server, 1400);
// Translate the passed message into ASCII and store it as a Byte array.
Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
// Get a client stream for reading and writing.
// Stream stream = client.GetStream();
NetworkStream stream = client.GetStream();
// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length);
//Console.WriteLine("Sent: {0}", message);
// Receive the TcpServer.response.
// Buffer to store the response bytes.
data = new Byte[256];
// String to store the response ASCII representation.
String responseData = String.Empty;
// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
//Console.WriteLine("Received: {0}", responseData);
// Close everything.
stream.Close();
client.Close();
}
catch (ArgumentNullException e)
{
//Console.WriteLine("ArgumentNullException: {0}", e);
}
catch (SocketException e)
{
// Console.WriteLine("SocketException: {0}", e);
}
//Console.WriteLine("\n Press Enter to continue...");
//Console.Read();
}
Now, how would I go about doing this with Windows 10 IoT on a Raspberry Pi 3?
With UWP, you may need to reference the "System.Net.Sockets" Nuget package in order to use TcpClient. You probably end up with something like below snippet,
async void FunctionName()
{
try
{
using (var client = new TcpClient())
{
await client.ConnectAsync(server, 1400);
// Translate the passed message into ASCII and store it as a Byte array.
Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
// Get a client stream for reading and writing.
// Stream stream = client.GetStream();
NetworkStream stream = client.GetStream();
// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length);
//Console.WriteLine("Sent: {0}", message);
// Receive the TcpServer.response.
// Buffer to store the response bytes.
data = new Byte[256];
// String to store the response ASCII representation.
String responseData = String.Empty;
// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
//Console.WriteLine("Received: {0}", responseData);
}
}
catch (ArgumentNullException e)
{
//Console.WriteLine("ArgumentNullException: {0}", e);
}
catch (SocketException e)
{
// Console.WriteLine("SocketException: {0}", e);
}
//Console.WriteLine("\n Press Enter to continue...");
//Console.Read();
}
Note that you need to declare the Internet client capability in your project manifest file.
PS: There's also an alternative an alternative called StreamSocket.
Refer to an complete code sample from Microsoft github repository.
Also, if you're new to UWP programming, you should get yourself familar with the async/await pattern.
Platform: WPF (.NET 4.5).
In order to check Internet connection as fast as it's possible I use this function:
[DllImport("wininet.dll")]
public extern static bool InternetCheckConnection(string lpszUrl, int dwFlags, int dwReserved);
The problem is that if I'm connected to the Internet and my program is executing InternetCheckConnection, it returns true (as expected) BUT if than I sleep the program for a moment and during this moment I disconnect my computer from the Internet and after that I check connection once again, than I have still true returned!
Why?!
I've prepared code that presents the problem:
using System;
using System.Runtime.InteropServices;
using System.Threading;
namespace InternetCheckConnectionTest
{
class Program
{
[DllImport("wininet.dll")]
public extern static bool InternetCheckConnection(string lpszUrl, int dwFlags, int dwReserved);
static void Main(string[] args)
{
string www = "http://www.google.com/";
Console.WriteLine("Checking connection...");
bool connected = InternetCheckConnection(www, 1, 0);
Console.WriteLine("Connection check returned " + connected.ToString());
TimeSpan ts = new TimeSpan(0, 0, 20);
Console.WriteLine("\nYou have " + ts.TotalSeconds.ToString() + " seconds to (dis)connect from/to the Internet.\n");
Thread.Sleep(ts);
Console.WriteLine("Checking connection once again...");
connected = InternetCheckConnection(www, 1, 0);
Console.WriteLine("Connection (2nd) check returned " + connected.ToString());
}
}
}
Before starting this program make sure that you are connected to the Internet. After this message:
You have 20 seconds to (dis)connect from/to the Internet.
disconnect from the Internet. You'll see that InternetCheckConnection(www, 1, 0) returns True even if you are disconnected from the Internet. The question is why?
I have a code to send and receive UDP socket
Send UDP code:
public static void main(String args[]) throws Exception
{
try
{
FileOutputStream fo = new FileOutputStream("OUTFILE.txt");
PrintStream ps = new PrintStream(fo);
DatagramSocket Socket = new DatagramSocket(4555);
byte[] receiveData = new byte[1000000];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
while(true)
{
receivePacket.setLength(receiveData.length);
Socket.receive(receivePacket);
String sentence = new String( receivePacket.getData());
System.out.printf("RECEIVED: %s " , new String(receivePacket.getData()));
ps.println(sentence);
ps.println();
ps.close();
fo.close();
}
File file = new File("OUTFILE.txt");
FileInputStream fis = new FileInputStream(file);
byte[] fsize = new byte[(int) file.length()];
int size = fis.read(fsize);
System.out.println("Received Size = " + size);
}
catch (Exception e) {
System.err.println(e);
}
}
}
I want to write the value of each received data packet into file then get the size of the whole file.
In my code I just got the first received value written in the file.
Could you please tell me how can I write the whole received value in the file.
At the end of the first loop, you're closing the streams so additional lines can not be written. You need to move the ps.close(); and fs.close() calls to be outside of the loop. In addition, you have an indefinite loop which guarantees that the code reading from the file can not be called--you need to have some mechanism to determine when to stop looping.
I basically try to reproduce the Socket example from here: http://www.silverlightshow.net/items/Sockets-and-their-implementation-in-SL2-Beta-1-including-a-chat-like-example.aspx
I only made a small change in the client side, i.e.,
String safeHost = "127.0.0.1";
int port = 4509;
Then I got this permission error? Any idea why?
Unhandled Error in Silverlight Application An attempt was made to access a socket in a way forbidden by its access permissions.
I believe that the way the socket security checks work you need to use the same url string that your application uses. to make sure i am using the correct string i have always used this to construct my DNSEndPoint:
int Port = 4509;
DnsEndPoint ep = new DnsEndPoint(Application.Current.Host.Source.DnsSafeHost, Port, AddressFamily.InterNetwork);
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.NoDelay = true;
SocketAsyncEventArgs ea = new SocketAsyncEventArgs{RemoteEndPoint = ep};
//set up completed event handler et al.
sock.ConnectAsync(ea);
I have used this exact code in a similar chat application. By using the Application.Current.Host.Source.DnsSafeHost Property you ensure that you are using the same Dns Name to access the server with the socket that the browser is using for HttpRequests.
Also are you serving the access policy file on port 943, this is another requirement of the socket support in Silverlight.
EDIT
To Confirm that you are serving the policy file you can do a number of things.
install Fiddler, you can use it to debug all http traffic hitting your server, you should be able to see the request for the policy file.
serve your policy file dynamically and then set a break point in your server application to confirm that it is being served. this is what i did.
here is the code i used to serve the policy file:
public abstract class Server
{
protected Socket Listener { get; set; }
protected int Port { get; private set; }
protected int Backlog { get; private set; }
protected bool isStopped { get; set; }
protected SocketAsyncEventArgs AcceptArgs {get;set;}
public Server(int port)
{
AcceptArgs = new SocketAsyncEventArgs();
AcceptArgs.Completed += new EventHandler<SocketAsyncEventArgs>(Accept_Completed);
isStopped = true;
Port = port;
Backlog = 100;
}
public Server(int port, int backlog)
{
isStopped = true;
Port = port;
Backlog = backlog;
}
public void Start()
{
isStopped = false;
Listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ep = new IPEndPoint(IPAddress.Any, Port);
Listener.ExclusiveAddressUse = true;
Listener.Bind(ep);
//Console.WriteLine("Listening on " + Port);
Listener.Listen(Backlog);
Listener.AcceptAsync(AcceptArgs);
}
void Accept_Completed(object sender, SocketAsyncEventArgs e)
{
if (isStopped) return;
Socket client = e.AcceptSocket;
//Console.WriteLine("Accepted Connection From: " + client.RemoteEndPoint.ToString());
e.AcceptSocket = null;
Listener.AcceptAsync(AcceptArgs);
HandleClient(client);
}
public virtual void Stop()
{
if (isStopped) throw new InvalidOperationException("Server already Stopped!");
isStopped = true;
try
{
Listener.Shutdown(SocketShutdown.Both);
Listener.Close();
}
catch (Exception)
{
}
}
protected abstract void HandleClient(Socket Client);
}
public class PolicyServer : Server
{
public const String policyStr = #"<?xml version=""1.0"" encoding=""utf-8"" ?>
<access-policy>
<cross-domain-access>
<policy>
<allow-from>
<domain uri=""*"" />
</allow-from>
<grant-to>
<socket-resource port=""4530"" protocol=""tcp"" />
</grant-to>
</policy>
</cross-domain-access>
</access-policy>";
private byte[] policy = Encoding.ASCII.GetBytes(policyStr);
private static string policyRequestString = "<policy-file-request/>";
public PolicyServer(): base(943)
{
}
protected override void HandleClient(Socket socket)
{
TcpClient client = new TcpClient { Client = socket };
Stream s = client.GetStream();
byte[] buffer = new byte[policyRequestString.Length];
client.ReceiveTimeout = 5000;
s.Read(buffer, 0, buffer.Length);//read in the request string, but don't do anything with it
//you could confirm that it is equal to the policyRequestString
s.Write(policy, 0, policy.Length);
s.Flush();
socket.Shutdown(SocketShutdown.Both);
socket.Close(1);
client.Close();
}
}
Then to use it:
PolicyServer ps = new PolicyServer();
ps.Start();
//then when shutting down
ps.Stop();
I hosted this "server" in the same process that was running the rest of the Chat Server component. Set a breakpoint in HandleClient to confirm if it is receiving the request.