How to make global access to server?
In code ,server its our local ip. On router, i create Wan Virtual server, but i cant send msg from global network.
I need to send msg from global client. And how i can save clients ip?
Thank in advance! I hope you understand my speech.
//Server
TcpListener Server = null;
try
{
Int32 port = 9595;
int MaxProc = Environment.ProcessorCount * 4;
Console.Write(GetIp()+":"+port.ToString());
Console.Write("\nCount proc * 4:"+MaxProc.ToString());
ThreadPool.SetMaxThreads(MaxProc, MaxProc);
ThreadPool.SetMinThreads(2, 2);
IPAddress LocalIp = IPAddress.Parse(GetIp());
int count = 0;
Server = new TcpListener(LocalIp,port);
Server.Start();
int max, countmax;
while(true)
{
Console.Write("\nWaiting for a connection... ");
ThreadPool.QueueUserWorkItem(ProcessMsg,Server.AcceptTcpClient());
ThreadPool.GetAvailableThreads(out max, out countmax);
Console.Write("\n Max:" + max.ToString() + "--Count:" + countmax.ToString());
count++;
Console.Write("\nConnection#"+count.ToString());
}
//Client
Int32 port = 9595;
TcpClient client = new TcpClient(server, port);
Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
NetworkStream stream = client.GetStream();
stream.Write(data, 0, data.Length);
Related
So this is code for my TCP based chat server written in c#. It works no problem for connecting two computers via ipv4 for chat, but I am wanting the server program to listen for and accept, then send a "sucessfully joined" message to the computers that joined.
I am wondering is there a way to change this code to do this?
Server code:
IPAddress ipAd = IPAddress.Parse(IPV4.Text); //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();
MessageBox.Show("The server is running at port 8001...");
MessageBox.Show("The local End point is :" + myList.LocalEndpoint);
MessageBox.Show("Looking for other computer");
Socket s = myList.AcceptSocket();
Console.WriteLine("Found buddy " + s.RemoteEndPoint);
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes(satt.Text));
MessageBox.Show("The message " + satt.Text + " was sent to the computer with IP address " + IPV4.Text);
byte[] b = new byte[100];
int k = s.Receive(b);
for (int i = 0; i < k; i++)
Console.Write(Convert.ToChar(b[i]));
/* clean up */
s.Close();
myList.Stop();
Client code:
TcpClient tcpclnt = new TcpClient();
tcpclnt.Connect(RecieveIPAdd.Text, 8001); // use the ipaddress as in the server program
MessageBox.Show("Connected");
Stream stm = tcpclnt.GetStream();
MessageBox.Show("Listening for attack information......");
byte[] bb = new byte[100];
int k = stm.Read(bb, 0, 100);
string atk = Encoding.UTF8.GetString(bb.AsSpan(0, k));
Thank you.
// Code after help
private void Connectnattk_DoWork(object sender, DoWorkEventArgs e)
{
{
{
try
{
IPAddress ipAd = IPAddress.Parse(IPV4.Text); //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();
MessageBox.Show("The server is running at port 8001...");
MessageBox.Show("The local End point is :" + myList.LocalEndpoint);
MessageBox.Show("Looking for other computer");
Socket s = myList.AcceptSocket();
Console.WriteLine("Found buddy " + s.RemoteEndPoint);
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes(satt.Text));
MessageBox.Show("The command " + satt.Text + " was sent to the computer with IP address " + IPV4.Text);
byte[] b = new byte[100];
int k = s.Receive(b);
for (int i = 0; i < k; i++)
Console.Write(Convert.ToChar(b[i]));
void ServerStart()
{
TcpListener listener = new TcpListener(IPAddress.Any, 8001);
listener.Start();
Console.WriteLine("Listening on port: 8001");
while (true)
{
TcpClient client = listener.AcceptTcpClient();
ThreadPool.QueueUserWorkItem(state => HandleConnection(client));
}
}
void HandleConnection(TcpClient client)
{
Socket s = myList.AcceptSocket();
Console.WriteLine("Found buddy " + s.RemoteEndPoint);
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes(satt.Text));
Console.WriteLine("Number of connected buddies: " + connectedbuddies++);
client.Close();
}
/* clean up */
s.Close();
myList.Stop();
}
Accepting a client socket in your code is synchronous, so you can only accept one client, process it then loop around to accept and process another.
You can use threads to add parallelism to your code. You create a method for handling client sockets and create a new thread for the client socket. This will allow you to continue looping to accept new incoming client socket connections whilst processing existing client socket connections.
static void ServerStart()
{
TcpListener listener = new TcpListener(IPAddress.Any, 4480);
listener.Start();
Console.WriteLine("Listening on port: 4480");
while (true)
{
// Accept the client connection before creating the thread.
TcpClient client = listener.AcceptTcpClient();
ThreadPool.QueueUserWorkItem(state => HandleConnection(client));
}
}
static void HandleConnection(TcpClient client)
{
// Insert your code here. (Do not accept socket again here)
client.Close();
}
I create a new thread to run the HandleConnection method for each TcpClient using ThreadPool. You can create threads without ThreadPool however if threads are short-lived for performance reasons, you will want to use ThreadPool to create them.
So I am writing a c# client server program where the client receives information from the server, however the client appears to try to send information rather than receive after the successfully connect
public void SL_Click(object sender, EventArgs e)
{
try
{
TcpClient tcpclnt = new TcpClient();
tcpclnt.Connect(RecieveIP.Text, 8001); // use the ipaddress as in the server program
MessageBox.Show("Connected");
String str = Console.ReadLine();
Stream stm = tcpclnt.GetStream();
ASCIIEncoding asen = new ASCIIEncoding();
byte[] ba = asen.GetBytes(str);
MessageBox.Show("Listening for information......");
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]));
string toattk = str.ToString();
I think this, as the client and server do successfully connect, but the the message sent from the server is never actually recieved.
Server code for action when it connects and sends the message to the other computer:
private void Connectnattk_DoWork(object sender, DoWorkEventArgs e)
{
try
{
IPAddress ipAd = IPAddress.Parse(ipv4.Text); //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();
MessageBox.Show("The server is running at port 8001...");
MessageBox.Show("The local End point is :" + myList.LocalEndpoint);
MessageBox.Show("Looking for other computer");
Socket s = myList.AcceptSocket();
Console.WriteLine("Found buddy " + s.RemoteEndPoint);
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes(satt.Text));
MessageBox.Show("The command " + satt.Text + " was sent to the computer with IP address " + ipv4.Text);
byte[] b = new byte[100];
int k = s.Receive(b);
for (int i = 0; i < k; i++)
Console.Write(Convert.ToChar(b[i]));
/* clean up */
s.Close();
myList.Stop();
}
catch (Exception)
{
MessageBox.Show("Could not find other computer.");
}
They connect no problem, but the message sent from the server never appears on the client. I surmise this is because the client is trying to send a response back rather than receiving the message sent by the server. Or are there other reasons why the message is not received despite the computers connected? Thank you.
I am working on a project that transfers files over TCP. It is written in .NET 4.7. The program works while the client connects on the server that is on the same computer but when I send it to a friend and I try to connect it I get an error:
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
Currently the program only sends some information about the file that will be copied and is nothing is encrypted as I cannot send even these information.
Here's the code for the server (Invoke is used because it is run on a separate thread):
private void Server_Start()
{
try
{
// Set port on 13000
int port = 13000;
//Get the ip adress for the server
String localIp;
using (var client = new WebClient())
{
// Try connecting to Google public DNS and get the local endpoint as IP
// If failed to connect set IP as local IP
if (CheckForInternetConnection())
{
try
{
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
{
socket.Connect("8.8.8.8", 65530);
IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
localIp = endPoint.Address.ToString();
}
}
catch (Exception e)
{
localIp = "127.0.0.1";
}
}
else
{
localIp = "127.0.0.1";
}
}
IPAddress IP = IPAddress.Parse(localIp);
// Create listener and start listening
server = new TcpListener(IP, port);
server.Start();
// Buffer for data
Byte[] bytes = new byte[256];
String data = string.Empty;
this.Invoke((MethodInvoker)(() => Log.Items.Add("Server started on ip: " + IP.ToString())));
while (true)
{
// Accepting requests
TcpClient client = server.AcceptTcpClient();
// Get the stream object
NetworkStream stream = client.GetStream();
// Read length of file name
byte[] nameLength = new byte[4];
stream.Read(nameLength, 0, 4);
int nameSize = BitConverter.ToInt32(nameLength, 0);
// Read the name of file
byte[] name = new byte[nameSize];
stream.Read(name, 0, nameSize);
String fileName = Encoding.UTF8.GetString(name);
// Read size of file
byte[] fileSizeB = new byte[4];
stream.Read(fileSizeB, 0, 4);
int fileSize = BitConverter.ToInt32(fileSizeB, 0);
// Read start signal
byte[] startB = new byte[9+1];
stream.Read(startB, 0, 9);
String start = Encoding.UTF8.GetString(startB);
this.Invoke((MethodInvoker)(() => Log.Items.Add("Size of name: " + nameSize.ToString())));
this.Invoke((MethodInvoker)(() => Log.Items.Add("Name of file: " + fileName)));
this.Invoke((MethodInvoker)(() => Log.Items.Add("File size: " + fileSize.ToString())));
this.Invoke((MethodInvoker)(() => Log.Items.Add("Start signal: " + start)));
// Response to client
byte[] message = Encoding.UTF8.GetBytes("Testmessage");
stream.Write(message, 0, message.Length);
}
server.Stop();
Log.Items.Add("Server started on ip: " + IP.ToString());
}
catch (Exception e)
{
this.Invoke((MethodInvoker)(() => Log.Items.Add(e)));
}
}
And here is the code for the client:
private void button1_Click(object sender, EventArgs e)
{
IPAddress iP = IPAddress.Parse(ConnectIp.Text);
int port = 13000;
int buffersize = 1024;
TcpClient client = new TcpClient();
NetworkStream netStream;
// Try to connect to server
try
{
client.Connect(new IPEndPoint(iP, port));
}
catch(Exception ex)
{
this.Invoke((MethodInvoker)(() => Log.Items.Add(ex.Message)));
return;
}
netStream = client.GetStream();
String path = "D:\\testingEnv\\test1\\testing\\Matematika\\2017\\Školsko\\2017-SS-skolsko-B-1234-zad.pdf";
String Filename = Path.GetFileName(path);
// We wish to send some data in advance:
// File name, file size, number of packets, send start and send end
byte[] data = File.ReadAllBytes(path);
// First packet contains: name size, file name, file size and "sendStart" signal
byte[] nameSize = BitConverter.GetBytes(Encoding.UTF8.GetByteCount(Filename)); // Int
byte[] nameB = Encoding.UTF8.GetBytes(Filename);
byte[] fileSize = BitConverter.GetBytes(data.Length);
byte[] start = Encoding.UTF8.GetBytes("sendStart");
// Last packet constains: "sendEnd" signal to stop reading netStream
byte[] end = Encoding.UTF8.GetBytes("sendEnd");
// Creating the first package: nameSize, fileName, fileSize and start signal
byte[] FirstPackage = new byte[4 + nameB.Length + 4 + 9];
nameSize.CopyTo(FirstPackage, 0);
nameB.CopyTo(FirstPackage, 4);
fileSize.CopyTo(FirstPackage, 4 + nameB.Length);
start.CopyTo(FirstPackage, 4 + nameB.Length + 4);
// Send the first pckage
netStream.Write(FirstPackage, 0, FirstPackage.Length);
byte[] buffer = new byte[30];
// Read the response
netStream.Read(buffer, 0, 11);
netStream.Close();
client.Close();
}
A friend tried to port forward the port 13000 but it didn't work either. We even tried with the firewall being down but nothing. I searched on the internet but couldn't find any solutions to the problem.
One thing to note is that both functions are in the same application. I don't know if that is the cause of the problem.
Does anyone know how what is the problem here?
Thanks in advance
Have you tried to connect to your server with telnet ? "telnet localhost 13000" or from other computer with correct ip and address nbr ? Try that while debugging your server code. If telnet works, then client code has some problem..
I'm trying to implement ping based on udp packets with C#. The idea is to send udp packets to wrong port and get back ICMP packets contating Port unreachable error. And the time elapsed between seding the udp packet and recieveing the icmp packet is a ping time. I do it like that:
// Start building the headers
//Console.WriteLine("Building the packet header...");
int messageSize = 64;
byte[] builtPacket, payLoad = new byte[messageSize];
UdpHeader udpPacket = new UdpHeader();
ArrayList headerList = new ArrayList();
Socket rawSocket = null;
SocketOptionLevel socketLevel;
// Initialize the payload
//Console.WriteLine("Initialize the payload...");
for (int i = 0; i < payLoad.Length; i++)
payLoad[i] = (byte)'0';
// Fill out the UDP header first
//Console.WriteLine("Filling out the UDP header...");
udpPacket.SourcePort = 33434;
udpPacket.DestinationPort = 33434;
udpPacket.Length = (ushort)(UdpHeader.UdpHeaderLength + messageSize);
udpPacket.Checksum = 0;
Ipv4Header ipv4Packet = new Ipv4Header();
// Build the IPv4 header
//Console.WriteLine("Building the IPv4 header...");
ipv4Packet.Version = 4;
ipv4Packet.Protocol = (byte)ProtocolType.Udp;
ipv4Packet.Ttl = 30;
ipv4Packet.Offset = 0;
ipv4Packet.Length = (byte)Ipv4Header.Ipv4HeaderLength;
ipv4Packet.TotalLength = (ushort)Convert.ToUInt16(Ipv4Header.Ipv4HeaderLength + UdpHeader.UdpHeaderLength + messageSize);
ipv4Packet.SourceAddress = sourceAddress;
ipv4Packet.DestinationAddress = destAddress;
// Set the IPv4 header in the UDP header since it is required to calculate the
// pseudo header checksum
//Console.WriteLine("Setting the IPv4 header for pseudo header checksum...");
udpPacket.ipv4PacketHeader = ipv4Packet;
// Add IPv4 header to list of headers -- headers should be added in th order
// they appear in the packet (i.e. IP first then UDP)
//Console.WriteLine("Adding the IPv4 header to the list of header, encapsulating packet...");
headerList.Add(ipv4Packet);
socketLevel = SocketOptionLevel.IP;
// Add the UDP header to list of headers after the IP header has been added
//Console.WriteLine("Adding the UDP header to the list of header, after IP header...");
headerList.Add(udpPacket);
// Convert the header classes into the binary on-the-wire representation
//Console.WriteLine("Converting the header classes into the binary...");
builtPacket = udpPacket.BuildPacket(headerList, payLoad);
// Create the raw socket for this packet
//Console.WriteLine("Creating the raw socket using Socket()...");
rawSocket = new Socket(sourceAddress.AddressFamily, SocketType.Raw, ProtocolType.Udp);
// Bind the socket to the interface specified
//Console.WriteLine("Binding the socket to the specified interface using Bind()...");
IPAddress bindAddress = IPAddress.Any;
rawSocket.Bind(new IPEndPoint(bindAddress, 0));
// Set the HeaderIncluded option since we include the IP header
//Console.WriteLine("Setting the HeaderIncluded option for IP header...");
rawSocket.SetSocketOption(socketLevel, SocketOptionName.HeaderIncluded, 1);
rawSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 1000);
Stopwatch timer = new Stopwatch();
try {
for (int i = 0; i < 5; i++) {
timer.Reset();
timer.Start();
int rc = rawSocket.SendTo(builtPacket, new IPEndPoint(destAddress, 0));
Console.WriteLine("Sent {0} bytes to {1}", rc, destAddress);
Socket icmpListener = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp);
icmpListener.Bind(new IPEndPoint(sourceAddress, 0));
icmpListener.IOControl(IOControlCode.ReceiveAll, new byte[] { 1, 0, 0, 0 }, new byte[] { 1, 0, 0, 0 });
icmpListener.Shutdown(SocketShutdown.Send);
byte[] buffer = new byte[4096];
EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
try {
int bytesRead = icmpListener.ReceiveFrom(buffer, ref remoteEndPoint);
timer.Stop();
Console.WriteLine("Recieved " + bytesRead + " bytes from " + destAddress + " in " + timer.ElapsedMilliseconds + "ms\n");
}
catch {
Console.WriteLine("Server is not responding!");
}
finally {
icmpListener.Close();
}
}
}
catch (SocketException err) {
Console.WriteLine("Socket error occurred: {0}", err.Message);
}
finally {
rawSocket.Close();
}
And it works from time to time. The thing is that some web-sites send me an icmp packet and some not. Actually at first they also were not sending then I used Windows ping to ping them and tracert to traceroute them. And changed port number and it worked. But not for all. I can ping only google.com and one more site but others don't send icmp packet back. The same situation with local network computers I tried to ping. I send udp packet and don't get icmp back.
I used wireshark to watch packets flying.
What am I doing wrong in here?
I am working on my project where I have to communicate between my tcp server written in c# on windows and my client written in python on raspbian (raspberry pi). My server is working fine (tested on local machine with client in c#), but when run client data isn't sent to the server side.
c# code:
static void Main(string[] args)
{
IPAddress localAdd = IPAddress.Parse(SERVER_IP);
TcpListener listener = new TcpListener(localAdd, PORT_NO);
Console.WriteLine("Krenuo sa radom...");
listener.Start();
while (true)
{
TcpClient client = listener.AcceptTcpClient();
NetworkStream nwStream = client.GetStream();
byte[] buffer = new byte[client.ReceiveBufferSize];
int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);
string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Primljeno : " + dataReceived);
Console.WriteLine("Dobijena poruka na serveru : " + dataReceived);
nwStream.Write(buffer, 0, bytesRead);
Console.WriteLine("\n");
client.Close();
}
listener.Stop();
python code:
def send(ctrl_cyc):
HOST, PORT = "10.93.34.41", 5000
data = ""
data += str(ctrl_cyc)
# Create a socket (SOCK_STREAM means a TCP socket)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# Connect to server and send data
sock.connect((HOST, PORT))
sock.sendall(bytes(data + "\n", "utf-8"))
finally:
sock.close()
return True
I found solution... Well i think I found it.
The thing is that probably my account doesn't have rights to listen other devices in network (network configuration). I tried my solution on admin's computer and it is working, and also I put it on company's server and it is working just fine.
Here are codes if anyone needs them.
c# code:
static void Main(string[] args)
{
IPAddress localAdd = IPAddress.Parse(SERVER_IP);
TcpListener listener = new TcpListener(IPAddress.Any, PORT_NO);
Console.WriteLine("Krenuo sa radom...");
listener.Start();
while (true)
{
TcpClient client = listener.AcceptTcpClient();
NetworkStream nwStream = client.GetStream();
byte[] buffer = new byte[client.ReceiveBufferSize];
int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);
string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Primljeno : " + dataReceived);
Console.WriteLine("Dobijena poruka na serveru : " + dataReceived);
nwStream.Write(buffer, 0, bytesRead);
Console.WriteLine("\n");
client.Close();
}
listener.Stop();
}
python code:
import socket
HOST, PORT = "10.XX.XX.XX", 5000
ctrl_cyc="1234567"
data = ""
data += str(ctrl_cyc)
# Create a socket (SOCK_STREAM means a TCP socket)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# Connect to server and send data
sock.connect((HOST, PORT))
sock.sendall(bytes(data + "\n"))
data = sock.recv(1024)
print data
finally:
sock.close()
When you bind to a specific IP Address, the server only listens on the interface used for this IP Address. So if you have more then one Network adapter and you want to listen on all of them, use IpAddress.Any in the Constructor of the TcpListener.
If this is not the case, could you give us some more information:
Is the client giving any error information/exception? Have you sniffed the Traffic between client and server? Is the connection established? ...