I've got a TCP server up and running on localhost on vs2010 on windows 2k8.
When I connect the client on 127.0.0.1 using vs2010, the server gets the call, (I can see it
from debug) as the tcp server executes the command line protocol handler, but the client does
recieve the server response, which is the session key, but blocks at the client when reading
the respone stream.
When I use Telnet on loopback for the same port, sending the same command sequence, the
response, i.e. the session key, is received instantaneously.
Here is the client code:
EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9121);
sing (Socket socket = new Socket(serverAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
{
socket.Connect(serverAddress);
var socketStream = new NetworkStream(socket);
var reader = new StreamReader(socketStream, Encoding.ASCII, false);
var writer = new StreamWriter(socketStream, Encoding.ASCII, 1024);
string charSource = Guid.NewGuid().ToString().Replace("-", string.Empty)
+ Guid.NewGuid().ToString().Replace("-", string.Empty)
+ Guid.NewGuid().ToString().Replace("-", string.Empty);
Random rd = new Random();
int startPos = rd.Next(0, charSource.Length - 2);
int endPos = rd.Next(startPos + 1, charSource.Length - 1);
var currentMessage = charSource.Substring(startPos, endPos - startPos + 1);
Console.WriteLine("Sent Command");
writer.Write("HEAR {0} {1}", currentMessage.Length.ToString().PadLeft(4, '0'), currentMessage);
writer.Flush();
Console.WriteLine("Reading Command Results");
var line = reader.ReadLine();
Console.WriteLine("Received: " + line);
}
Bob
To make this work, please change Write with WriteLine as shown in the code below:
Console.WriteLine("Sent Command");
writer.WriteLine("HEAR {0} {1}", currentMessage.Length.ToString().PadLeft(4, '0'), currentMessage);
writer.Flush();
Enable network tracing, so you can be sure that the data is comming. It probably is, so change your call to reader.Read and read until you find the end of the message.
Related
I am trying to find Lantronix XPort Pro devices on a network using C#. I am using some python code that I found on the Lantronix developer wiki as an example http://wiki.lantronix.com/developer/Lantronix_Discovery_Protocol.
The application I am writing is written in C# and I need to discover our units that have Lantronix devices installed. It seems that when I do the socket.RecieveFrom function call it just seems to hang the app.
Any ideas on what I am doing wrong. The python code from the link above detects the devices correctly. I should be able to duplicate this in C#.
Any help would be much appreciated.
private void FindLantronixXPort()
{
// This is the socket code that will broadcast from
// the local machine looking for responces from Lantronix
// XPort servers
// Create the array for our message chars
char[] chars = new char[4];
// Build the actual message
chars[0] = Convert.ToChar(0);
chars[1] = Convert.ToChar(0);
chars[2] = Convert.ToChar(0);
chars[3] = Convert.ToChar(0xf6);
// Convert the chars to a message string
string msg = new string(chars);
// Convert the setring to a byte array
byte[] data = Encoding.UTF8.GetBytes(msg);
// Get the local machines IP address
string Local_IP = GetIPAddress();
// Now create a broadcast UDP socket
Socket XmtSock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
XmtSock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
IPEndPoint iep = new IPEndPoint(IPAddress.Parse(Local_IP), LantronixPort);
// Broadcast the packet
XmtSock.SendTo(data, 0, data.Length, SocketFlags.None, iep);
XmtSock.Close();
// Wait 500 mili seconds
int milliseconds = 500;
System.Threading.Thread.Sleep(milliseconds);
Socket RcvSock = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
iep = new IPEndPoint(IPAddress.Any, LantronixPort);
RcvSock.Bind(iep);
EndPoint ep = (EndPoint)iep;
Console.WriteLine("Ready to receive...");
byte[] data1 = new byte[120];
int recv = RcvSock.ReceiveFrom(data1, data1.Length, SocketFlags.None, ref ep);
string stringData = Encoding.ASCII.GetString(data1, 0, recv);
Console.WriteLine("received: {0} from: {1}",
stringData, ep.ToString());
RcvSock.Close();
}
Lantronix's wiki seems to be down at the moment, so I can't take a look at that for the moment. However, looking at your code it seems that you have to broadcast a UDP message, wait some time, and then check to see if anything has responded to that message.
However, it looks like you're creating a brand new socket for receiving the responses, but only after half a second. It's highly likely that any X-port that is going to respond will already have done so long before then (networks are fast, X-ports aren't very sluggish, etc). So I reckon the responses are hitting your OS'es network stack, which saying "well I dunno where that's supposed to go", and only after half a second are you creating a socket suitable for receiving the responses that the OS'es network stack has already discarded as unknown junk.
So move things around a bit is what I suggest. Set up the receiving socket, binding and endpoint before you transmit the broadcast message, so that it's ready there waiting for responses. See if that helps.
#WJD Your code for preparing byte array did not create content expected by XPort. It is why it did not replyed and hang on RecieveFrom().
I followed the link you gave for python example and created version in C#.
class Program
{
static void Main(string[] args)
{
Socket socket;
int GroupPort = 30718;
try
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
var localEP = new IPEndPoint(IPAddress.Parse("10.0.2.14"), GroupPort); // <-- your local IP address
socket.Bind(localEP);
socket.ReceiveTimeout = 200;
}
catch (TimeoutException e)
{
Console.WriteLine("Failed to create socket. " + e.Message);
return;
}
var remoteEP = new IPEndPoint(IPAddress.Broadcast, GroupPort);
try
{
byte[] messageBytes;
messageBytes = new byte[0];
messageBytes = AddByteToArray(messageBytes, 0xf6);
messageBytes = AddByteToArray(messageBytes, 0);
messageBytes = AddByteToArray(messageBytes, 0);
messageBytes = AddByteToArray(messageBytes, 0);
socket.SendTo(messageBytes, remoteEP);
}
catch (Exception e)
{
Console.WriteLine("Failed to send message. " + e.Message);
return;
}
var recvEp = (EndPoint)new IPEndPoint(IPAddress.Any, 0);
while (true)
{
try
{
var recvBytes = new byte[1024];
var receivedCount = socket.ReceiveFrom(recvBytes, ref recvEp);
var receivedArray = recvBytes.Take(receivedCount).ToArray();
var receivedArrayAsHexString = string.Join("", receivedArray.Select(c => String.Format("{0:X2}", Convert.ToInt32(c))));
string returnData = Encoding.ASCII.GetString(receivedArray);
Console.WriteLine($"Broadcast Respond from client {recvEp.ToString()} returned: {receivedArrayAsHexString}");
}
catch (Exception e)
{
socket.Close();
break;
}
}
Console.ReadLine();
}
public static byte[] AddByteToArray(byte[] bArray, byte newByte)
{
byte[] newArray = new byte[bArray.Length + 1];
bArray.CopyTo(newArray, 1);
newArray[0] = newByte;
return newArray;
}
}
I am trying to send message over TCP/IP in c# application using TCPClient and TCPListner classes
Following is my code which i got from codeproject site.
Client code written over btn click
try
{
TcpClient tcpclnt = new TcpClient();
Console.WriteLine("Connecting.....");
tcpclnt.Connect("192.168.0.102", 8001);
// use the ipaddress as in the server program
Console.WriteLine("Connected");
//Console.Write("Enter the string to be transmitted : ");
String str = textBox1.Text;
Stream stm = tcpclnt.GetStream();
ASCIIEncoding asen = new ASCIIEncoding();
byte[] ba = asen.GetBytes(str);
Console.WriteLine("Transmitting.....");
stm.Write(ba, 0, ba.Length);
byte[] bb = new byte[100];
int k = stm.Read(bb, 0, 100);
for (int i = 0; i < k; i++)
Console.Write(Convert.ToChar(bb[i]));
tcpclnt.Close();
}
catch (Exception ex)
{
Console.WriteLine("Error..... " + ex.Message);
}
Server code written on form_load
try
{
IPAddress ipAd = IPAddress.Parse("192.168.0.102");
// use local m/c IP address, and
// use the same in the client
/* Initializes the Listener */
TcpListener myList = new TcpListener(ipAd, 8001);
/* Start Listeneting at the specified port */
myList.Start();
Console.WriteLine("The server is running at port 8001...");
Console.WriteLine("The local End point is :" +
myList.LocalEndpoint);
Console.WriteLine("Waiting for a connection.....");
Socket s = myList.AcceptSocket();
Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
byte[] b = new byte[100];
int k = s.Receive(b);
Console.WriteLine("Recieved...");
string str = string.Empty;
for (int i = 0; i < k; i++)
{
Console.Write(Convert.ToChar(b[i]));
str = str + Convert.ToChar(b[i]);
}
label1.Text = str;
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes("The string was recieved by the server."));
Console.WriteLine("\nSent Acknowledgement");
/* clean up */
s.Close();
// myList.Stop();
}
Here on client, i m sending string written in textbox over tcp and it well recieved by server.
But when i trying to send another string, it fails without any exception and client application hangs for infinite time.
What is wrong here ?
Server should always be in listening mode, i.e the server code should be in while loop such that it can accept clients continuously. Your server will accept one client and then close itself. Therefore, if you click client's button, a new client tries to connect to server, but now the server won't be available.
Looking at the code you provided, the server only attempts to read 1 message from the client, so needs to be put in a loop to read the multiple incoming messages from the client, process the message and send response and then get more messages.
Note also that the server currently expects only one client to ever connect, processes that client and then closes.
The client is set up basically the same in the example, so you cant modify how one works without also modifying the other.
I've been coding a chat program that is made of two parts: server and client. The server uses TcpListener to listen for incoming requests to join the server, and the client uses TcpClient that it uses to connect to the server, and send messages. So far I have the handshake that is the first message sent when the client connects - it contains the client's IP address and the nickname set. I don't know how to make the server to listen asynchronously, because if it's not async, then the chat will be client -> server -> client -> server whereas it needs to be connected to multiple clients at once, and receive multiple messages at once. My code so far is written synchronously:
Client:
public void StartClient(string serverIP)
{
ReadWrite rw = new ReadWrite();
string nick = rw.GetNick();
string handshakeContents = "HANDSHAKE:" + nick + ":" + GetIP();
Int32 serverPort = 1336; // yay
TcpClient client = new TcpClient(serverIP, serverPort);
Console.WriteLine("Sending initial handshake: {0}", handshakeContents);
Byte[] data = System.Text.Encoding.ASCII.GetBytes(handshakeContents); // Convert handshakeContents to Byte[]
NetworkStream stream = client.GetStream(); // Instantiate object "stream" for use in read/write
stream.Write(data, 0, data.Length); // Send handshakeContents in Byte[] to server
Console.WriteLine(" - Connecting to IlanChat Server on ip {0}", serverIP);
Thread.Sleep(1000); // sleep 1s
data = new Byte[256];
string responseHandshake = String.Empty; // response handshake from server
Int32 bytes = stream.Read(data, 0, data.Length); // Read handshake.
responseHandshake = System.Text.Encoding.ASCII.GetString(data, 0, bytes); // Decode from Byte[] to ASCII string
Console.WriteLine(" - Received response handshake: {0}", responseHandshake);
Console.WriteLine(" - Successfully connected to IlanChat server on IP {0}", serverIP); // display message
Thread.Sleep(2000);
Console.Clear();
List<string> messagesRecieved = new List<string>();
while(true)
{
Console.Clear();
foreach (string msg in messagesRecieved)
{
Console.WriteLine(msg);
}
Console.WriteLine();
Console.Write("Enter message: ");
string msgRaw = Console.ReadLine();
string sendMsg = nick + ": " + msgRaw;
data = new Byte[256];
data = System.Text.Encoding.ASCII.GetBytes(sendMsg);
stream.Write(data, 0, data.Length); // finish this async shit
}
}
Server:
List<string> clientIP = new List<string>();
List<string> clientNicks = new List<string>();
string responseHandshake = "hello";
Int32 serverPort = 1336;
IPAddress machineIP = IPAddress.Parse(GetIP());
Console.Clear();
Console.WriteLine(" - Starting IlanChat server on IP {0}", machineIP);
TcpListener server = null;
server = new TcpListener(machineIP, serverPort);
server.Start();
Byte[] buffer = new Byte[256];
String data = null;
Console.WriteLine("Successfully started IlanChat server!");
while (true) // first alpha - only one user at a time
{
Console.WriteLine();
Console.WriteLine("Waiting for connections..");
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("User connecting..");
Console.WriteLine("Receiving handshake data..");
data = null;
NetworkStream stream = client.GetStream();
int i;
while ((i = stream.Read(buffer, 0, buffer.Length)) != 0)
{
data = System.Text.Encoding.ASCII.GetString(buffer, 0, i);
Console.WriteLine("Received handshake data: {0}", data);
Console.WriteLine("Processing data.."); // sample handshake: - HANDSHAKE:nick:ip
string tempNick = data.Replace("HANDSHAKE:", "");
string[] userDetails = tempNick.Split(':'); // should store to 0:nick, 1:ip
Console.WriteLine("Received client nick: {0}", userDetails[0]);
Console.WriteLine("Received client IP: {0}", userDetails[1]);
break;
}
Thread.Sleep(1100); // sleep
buffer = System.Text.Encoding.ASCII.GetBytes(responseHandshake);
Console.WriteLine("Sending response handshake..");
stream.Write(buffer, 0, buffer.Length);
}
Is there a way to make the server accept multiple connections at once, and maintain them? And is there a way to make the client receive multiple messages at once and type while refreshing the messages?
You need to look at using threading (Task library, async/await) to do what you want. Try looking here:
https://codereview.stackexchange.com/questions/29000/c-console-chat-server-async-await-tcpclient-tcplistener-networkstream-asyn
To get you started, assuming the logic in your code is correct you want to split up the server/client, something like this:
static void RunServer()
{
List<string> clientIP = new List<string>();
List<string> clientNicks = new List<string>();
string responseHandshake = "hello";
Int32 serverPort = 1336;
IPAddress machineIP = IPAddress.Parse(GetIP());
Console.Clear();
Console.WriteLine(" - Starting IlanChat server on IP {0}", machineIP);
TcpListener server = null;
server = new TcpListener(machineIP, serverPort);
server.Start();
Byte[] buffer = new Byte[256];
String data = null;
Console.WriteLine("Successfully started IlanChat server!");
while (true) // first alpha - only one user at a time
{
Console.WriteLine();
Console.WriteLine("Waiting for connections..");
TcpClient client = server.AcceptTcpClient();
Task.Run(() => RunClient(client));
}
}
static void RunClient(TcpClient client)
{
Byte[] buffer = new Byte[256];
Console.WriteLine("User connecting..");
Console.WriteLine("Receiving handshake data..");
String data = null;
string responseHandshake = "hello";
NetworkStream stream = client.GetStream();
int i;
while ((i = stream.Read(buffer, 0, buffer.Length)) != 0)
{
data = System.Text.Encoding.ASCII.GetString(buffer, 0, i);
Console.WriteLine("Received handshake data: {0}", data);
Console.WriteLine("Processing data.."); // sample handshake: - HANDSHAKE:nick:ip
string tempNick = data.Replace("HANDSHAKE:", "");
string[] userDetails = tempNick.Split(':'); // should store to 0:nick, 1:ip
Console.WriteLine("Received client nick: {0}", userDetails[0]);
Console.WriteLine("Received client IP: {0}", userDetails[1]);
break;
}
Thread.Sleep(1100); // sleep
buffer = System.Text.Encoding.ASCII.GetBytes(responseHandshake);
Console.WriteLine("Sending response handshake..");
stream.Write(buffer, 0, buffer.Length);
}
Good afternoon. I apologize for my English as itself from Ukraine and speak badly)) I have the following problem, my program makes requests on different urls and then parse some info from answers. Number of urls are more than several millions. To quickly process I use a lot of threads, sometimes about 500-700 threads. On some machines program is running well, but there are those on which errors occur. Errors like: System.Net.Sockets.SocketException (0x80004005): The remote host forcibly broke the existing connection.
My code:
void _thread()
{
while(true)
{
string request =
"POST http://" + hostf + "/ HTTP/1.1\r\n" +
"Host: " + host +
"\r\nConnection: Close\r\n" +
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n" +
"Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3\r\n" +
"Content-Length: " + ByteArr.Length +
"\r\nContent-Type: application/x-www-form-urlencoded; charset=UTF-8\r\n\r\n" +
parametres;
Byte[] bytesSent = Encoding.GetEncoding("UTF-8").GetBytes(request);
Byte[] bytesReceived = new Byte[256];
Socket s = null;
IPHostEntry hostEntry = null;
hostEntry = Dns.GetHostEntry(host);
foreach (IPAddress address in hostEntry.AddressList)
{
IPEndPoint ipe = new IPEndPoint(address, 80);
Socket tempSocket =new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
tempSocket.Connect(ipe);
if (tempSocket.Connected)
{
s = tempSocket;
break;
}
else
{
continue;
}
}
if (s == null)
continue;
s.Send(bytesSent, bytesSent.Length, 0);
int bytes = 0;
string page = "";
do
{
bytes = s.Receive(bytesReceived, bytesReceived.Length, 0);
page = page + Encoding.GetEncoding("UTF-8").GetString(bytesReceived, 0, bytes);
}
while (bytes > 0);
s.Shutdown(SocketShutdown.Both);
s.Close();
//here some work whith page content
}
}
As you see, each thread creates socket, sends request, then get answer and closes socket and so on with each iteration. Each thread opens its own socket and works with different urls, but on some machines when numbers of threads are more than some number, the errors begin and all sockets don't work normally. Could someone help me with some advise, why does it happen? Some machines have some kind of limits on connection or what? Thank you all in advance.
Dont do the shutdown(both); followed by a close. Remove the s.shutdown() and leave the s.Close() then try. I think I remeber that shutdown both makes the socket descriptor available for use so in the next close you can be closing some other socket instead the one you owned.
EDIT: some code modification:
I'd increment a little bit the receive buffer
bytes[] bytesReceived = new bytes[1024];
Also when sending the request string tell the reciver you are done:
s.Send(bytesSent, bytesSent.Length, 0);
// Tell the receiver we are done sending data
s.Shutdown(SocketShutdown.Send);
You also have to check for error when reading the socket and use a StringBuilder instead of a String (it's somehow faster than String appending text):
StringBuilder page = new StringBuilder();
do
{
bytes = s.Receive(bytesReceived, bytesReceived.Length, 0);
if (bytes == -1)
{
// Error in socket, quit
s.Close();
return;
}
else if (bytes > 0)
page.Append(Encoding.GetEncoding("UTF-8").GetString(bytesReceived, 0, bytes));
}
while (bytes > 0);
At the end, just close the socket:
// s.ShutDown(Socketshutdown.Both);
s.close();
You may try with this modifications and see if it is solved.
I'm trying to send commands to the Tor control port programmatically to make it refresh the chain. I haven't been able to find any examples in C#, and my solution's not working. The request times out. I have the service running, and I can see it listening on the control port.
public string Refresh()
{
TcpClient client = new TcpClient("localhost", 9051);
string response = string.Empty;
string authenticate = MakeTcpRequest("AUTHENTICATE\r\n", client);
if (authenticate.Equals("250"))
{
response = MakeTcpRequest("SIGNAL NEWNYM\r\n", client);
}
client.Close();
return response;
}
public string MakeTcpRequest(string message, TcpClient client)
{
client.ReceiveTimeout = 20000;
client.SendTimeout = 20000;
string proxyResponse = string.Empty;
try
{
// Send message
StreamWriter streamWriter = new StreamWriter(client.GetStream());
streamWriter.Write(message);
streamWriter.Flush();
// Read response
StreamReader streamReader = new StreamReader(client.GetStream());
proxyResponse = streamReader.ReadToEnd();
}
catch (Exception ex)
{
// Ignore
}
return proxyResponse;
}
Can anyone spot what I'm doing wrong?
Edit:
Following Hans's suggestion, which he has now deleted for some reason, I tried to send "AUTHENTICATE\n" instead of just "AUTHENTICATE". Now I'm getting back an error from Tor: "551 Invalid quoted string. You need to put the password in double quotes." At least there's some progress.
I then tried to send "AUTHENTICATE \"\"\n", like it wants to, but it times out while waiting for a response.
Edit:
The command works fine in the Windows Telnet client. I don't even have to add the quotes. Can't figure out what's wrong. Maybe the double quotes aren't encoded correctly when they're sent?
public static void CheckIfBlocked(ref HtmlDocument htmlDoc, string ypURL, HtmlWeb hw)
{
if (htmlDoc.DocumentNode.InnerText.Contains("FORBIDDEN ACCESS!"))
{
Console.WriteLine("Getting Blocked");
Utils.RefreshTor();
htmlDoc = hw.Load(ypURL, "127.0.0.1", 8118, null, null);
if (htmlDoc.DocumentNode.InnerText.Contains("FORBIDDEN ACCESS!"))
{
Console.WriteLine("Getting Blocked");
Utils.RefreshTor();
}
}
}
public static void RefreshTor()
{
IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9051);
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
server.Connect(ip);
}
catch (SocketException e)
{
Console.WriteLine("Unable to connect to server.");
RefreshTor();
return;
}
server.Send(Encoding.ASCII.GetBytes("AUTHENTICATE \"butt\"\n"));
byte[] data = new byte[1024];
int receivedDataLength = server.Receive(data);
string stringData = Encoding.ASCII.GetString(data, 0, receivedDataLength);
if (stringData.Contains("250"))
{
server.Send(Encoding.ASCII.GetBytes("SIGNAL NEWNYM\r\n"));
data = new byte[1024];
receivedDataLength = server.Receive(data);
stringData = Encoding.ASCII.GetString(data, 0, receivedDataLength);
if (!stringData.Contains("250"))
{
Console.WriteLine("Unable to signal new user to server.");
server.Shutdown(SocketShutdown.Both);
server.Close();
RefreshTor();
}
}
else
{
Console.WriteLine("Unable to authenticate to server.");
server.Shutdown(SocketShutdown.Both);
server.Close();
RefreshTor();
}
server.Shutdown(SocketShutdown.Both);
server.Close();
}
When I send the AUTHENTICATE command, the StreamReader is reading the response to the end, but there is no end because on success the stream is kept open. So I changed it to only read the first line of the response in this case.
public static string MakeTcpRequest(string message, TcpClient client, bool readToEnd)
{
client.ReceiveTimeout = 20000;
client.SendTimeout = 20000;
string proxyResponse = string.Empty;
try
{
// Send message
using (StreamWriter streamWriter = new StreamWriter(client.GetStream()))
{
streamWriter.Write(message);
streamWriter.Flush();
}
// Read response
using (StreamReader streamReader = new StreamReader(client.GetStream()))
{
proxyResponse = readToEnd ? streamReader.ReadToEnd() : streamReader.ReadLine();
}
}
catch (Exception ex)
{
throw ex;
}
return proxyResponse;
}
Added another example I'm using myself below. Also added steps for those who would like to setup Tor that can accept commands through the control port.
Socket server = null;
//Authenticate using control password
IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9151);
server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
server.Connect(endPoint);
server.Send(Encoding.ASCII.GetBytes("AUTHENTICATE \"your_password\"" + Environment.NewLine));
byte[] data = new byte[1024];
int receivedDataLength = server.Receive(data);
string stringData = Encoding.ASCII.GetString(data, 0, receivedDataLength);
//Request a new Identity
server.Send(Encoding.ASCII.GetBytes("SIGNAL NEWNYM" + Environment.NewLine));
data = new byte[1024];
receivedDataLength = server.Receive(data);
stringData = Encoding.ASCII.GetString(data, 0, receivedDataLength);
if (!stringData.Contains("250"))
{
Console.WriteLine("Unable to signal new user to server.");
server.Shutdown(SocketShutdown.Both);
server.Close();
}
else
{
Console.WriteLine("SIGNAL NEWNYM sent successfully");
}
Steps to configure Tor:
Copy torrc-defaults into the directory in which tor.exe is. Default directory if you are using Tor browser is: "~\Tor Browser\Browser\TorBrowser\Data\Tor"
Open a cmd prompt window
chdir to the directory where tor.exe is. Default directory if you are using Tor browser is: "~\Tor Browser\Browser\TorBrowser\Tor\"
Generate a password for Tor control port access. tor.exe --hash-password “your_password_without_hyphens” | more
Add your password password hash to torrc-defaults under ControlPort 9151. It should look something like this: hashedControlPassword 16:3B7DA467B1C0D550602211995AE8D9352BF942AB04110B2552324B2507. If you accept your password to be "password" you can copy the string above.
You can now access Tor control via Telnet once it is started. Now the code can run, just edit the path to where your Tor files are located in the program.
Test modifying Tor via Telnet:
Start tor with the following command: tor.exe -f .\torrc-defaults
Open up another cmd prompt and type: telnet localhost 9151
If all goes well you should see a completely black screen. Type "autenticate “your_password_with_hyphens”" If all goes well you should see "250 OK".
Type "SIGNAL NEWNYM" and you will get a new route, ergo new IP. If all goes well you should see "250 OK".
Type "setevents circ" (circuit events) to enable console output
Type "getinfo circuit-status" to see current circuits
Probably you using Vidalia that generates a hashed password for control port access. You need to use Tor console app and configure a torrc file.