I'm going to setup a small client/server server in TCP/IP mode, I use VS2010,C# to develop my apps, I've googled a lot and could find some source codes, but none of them work in internet, I can get some answers in my own local system, i.e. I run my server, then listen for my own localhost (127.0.0.1) then send some data (for example using telnet), it works fine but when I do the same over internet I get nothing! I want to use port 80, as I want to send/receive http data, I have tested several source codes, here is the last code I have used (and it works on localhost with telnet)
//server code:
form_load()
IPAddress localAddress = IPAddress.Parse("127.0.0.1");
Socket listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipEndpoint = new IPEndPoint(localAddress, 80);
// Bind the socket to the end point
listenSocket.Bind(ipEndpoint);
// Start listening, only allow 1 connection to queue at the same time
listenSocket.Listen(1);
listenSocket.BeginAccept(new AsyncCallback(ReceiveCallback), listenSocket);
Console.WriteLine("Server is waiting on socket {0}", listenSocket.LocalEndPoint);
// Start being important while the world rotates
while (true)
{
Console.WriteLine("Busy Waiting....");
Thread.Sleep(2000);
}
public static void ReceiveCallback(IAsyncResult AsyncCall)
{
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
Byte[] message = encoding.GetBytes("I am a little busy, come back later!");
Socket listener = (Socket)AsyncCall.AsyncState;
Socket client = listener.EndAccept(AsyncCall);
Console.WriteLine("Received Connection from {0}", client.RemoteEndPoint);
client.Send(message);
Console.WriteLine("Ending the connection");
client.Close();
listener.BeginAccept(new AsyncCallback(ReceiveCallback), listener);
}
send data (client), of course I haven't used this code, is it right?
public static string SendData()
{
TcpClient client = new TcpClient();
client.Connect(IP, 80);
StreamWriter sw = new StreamWriter(client.GetStream());
StreamReader sr = new StreamReader(client.GetStream());
//if statement evalutes to see if the user has selected to update the server
//" " = update server
//"" = do not update the server
//if (updateData.Equals(""))
//{
// space = "";
//}
//else if (!updateData.Equals(""))
//{
// space = " ";
//}
//Refrences stream writer, username variable passed in from GUI
//space variable provides update function: "" = dont update. " " = update database.
sw.WriteLine("h");
sw.Flush();
//data send back from the server assigned to string variable
//string recieved = sr.ReadLine();
return "";
}
I'm going to have the server code in my Server (winserver 2008R2) but currently test it in normal PCs, what am I doing wrong? I want to send some http packet from a random system (with a random IP) to my server (which I know its IP), what should I do? is it possible with tcp/ip or I should do something else?
is it related to static IP? should I certainly have static IP? my web server has a static IP but my clients do not, is it a problem?
I think I have some problem in defining ports and IPs, how should I set them? my server has a specific IP, but I don't know IP of my clients, would you please explain it to me step by step?
thanks
The two most common problems in this scenario:
Ensure your server's router is using port forwarding to forward HTTP requests from the router to the server.
Ensure you are connecting to the server's public IP address, not its local network address.
Related
I am having trouble with my c# tcp code.
When I run the server and the client on the same computer, it will connect just fine.
But when I run the client on a different PC or on a phone, I get: 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.
Here is the server code:
private static void CreateServer()
{
TcpListener server = null;
try
{
Int32 port = 13000;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
server = new TcpListener(localAddr, port);
server.Start();
Byte[] bytes = new Byte[256];
String data = null;
while (true)
{
Console.Write("Waiting for a connection... ");
/*
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
var ipAddress = ipHostInfo.AddressList;
Console.WriteLine(ipHostInfo.HostName);
Console.WriteLine(ipAddress[0]);
*/
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
data = null;
NetworkStream stream = client.GetStream();
int i;
try
{
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", data);
data = data.ToUpper();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
stream.Write(msg, 0, msg.Length);
}
}
catch(IOException e)
{
//Console.WriteLine(e);
Console.WriteLine("Restarting Server");
//client.Close();
//CreateServer();
}
// Shutdown and end connection
client.Close();
}
}
catch (SocketException e)
{
//Console.WriteLine("SocketException: {0}", e);
}
finally
{
// Stop listening for new clients.
server.Stop();
}
Console.WriteLine("\nHit enter to continue...");
Console.Read();
}
I removed most of the comments. But that is the basic example for a tcp server from the documentation.
the client connect code is very simple:
tcpClient = new TcpClient();
tcpClient.Connect("192.168.0.7", 13000);
with the declaration for tcpClient saved in a less local spot for retaining and quickly reconnecting.
What I have tried:
I have made sure the IP address is correct, I even port forwarded and used my external IP, but got the same issue.
I made sure the firewall is not blocking the app on either device.
I tried using either device as the server.
I've looked up the problem and the only other person to have this issue needed to make sure he put in the correct IP and fix his firewall settings. I'm probably missing something super obvious.
One final piece of information, one device is wired to the router, I don't know if that is messing with anything.
One other thing, I tried:
tcpClient.Connect(new IPEndPoint(IPAddress.Parse("192.168.0.7"), 13000));
as well.
Whelp I was right. It was something very obvious and honestly dumb on my part.
on the server side:
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
does not result in the server listening on its ipv4, instead it listens on an ipv6
so what you want:
Remove the localAddr declaration, as it is not important, and instead of calling:
server = new TcpListener(localAddr, port);
call:
server = new TcpListener(IPAddress.Any, port);
IPAddress.Any is used to listen across all of the network interfaces the device has.
I'm trying to implement Hole punching using C# but unfortunately I spent hours to figure out why it doesn't work for me. Here is my problem:
I have a third part server that I can manage all external IPs for the peers on, and of course my router is behind a NAT, and I assume all my peers are also behind NATs.
Say if I managed to figure out all slaves (peers), End points (external ips). Where to put the external ip address of my server which runs on my pc (not the third party one), and where to put the peer ip address?
This is my code:
public void HolePunch(String ServerIp, Int32 Port) // if I put my external ip here I get Exception (An address incompatible with the requested protocol was used)
{
IPEndPoint LocalPt = new IPEndPoint(Dns.GetHostEntry(Dns.GetHostName()).AddressList[0], Port);
UdpClient Client = new UdpClient();
Client.ExclusiveAddressUse = false;
Client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
Client.Client.Bind(LocalPt);
IPEndPoint RemotePt = new IPEndPoint(IPAddress.Parse(ServerIp), Port);
// This Part Sends your local endpoint to the server so if the two peers are on the same nat they can bypass it, you can omit this if you wish to just use the remote endpoint.
byte[] IPBuffer = System.Text.Encoding.UTF8.GetBytes(Dns.GetHostEntry(Dns.GetHostName()).AddressList[0].ToString());
byte[] LengthBuffer = BitConverter.GetBytes(IPBuffer.Length);
byte[] PortBuffer = BitConverter.GetBytes(Port);
byte[] Buffer = new byte[IPBuffer.Length + LengthBuffer.Length + PortBuffer.Length];
LengthBuffer.CopyTo(Buffer,0);
IPBuffer.CopyTo(Buffer, LengthBuffer.Length);
PortBuffer.CopyTo(Buffer, IPBuffer.Length + LengthBuffer.Length);
Client.BeginSend(Buffer, Buffer.Length, RemotePt, new AsyncCallback(SendCallback), Client);
// Wait to receve something
BeginReceive(Client, Port);
// you may want to use a auto or manual ResetEvent here and have the server send back a confirmation, the server should have now stored your local (you sent it) and remote endpoint.
// you now need to work out who you need to connect to then ask the server for there remote and local end point then need to try to connect to the local first then the remote.
// if the server knows who you need to connect to you could just have it send you the endpoints as the confirmation.
// you may also need to keep this open with a keepalive packet untill it is time to connect to the peer or peers.
// once you have the endpoints of the peer you can close this connection unless you need to keep asking the server for other endpoints
Client.Close();
}
public void ConnectToPeer(String PeerIp, Int32 Port)
{
IPEndPoint LocalPt = new IPEndPoint(Dns.GetHostEntry(Dns.GetHostName()).AddressList[0], Port);
UdpClient Client = new UdpClient();
Client.ExclusiveAddressUse = false;
Client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
Client.Client.Bind(LocalPt);
IPEndPoint RemotePt = new IPEndPoint(IPAddress.Parse(PeerIp), Port);
Client.Connect(RemotePt);
//you may want to keep the peer client connections in a list.
BeginReceive(Client, Port);
}
public void SendCallback(IAsyncResult ar)
{
UdpClient Client = (UdpClient)ar.AsyncState;
Client.EndSend(ar);
}
public void BeginReceive(UdpClient Client, Int32 Port)
{
IPEndPoint ListenPt = new IPEndPoint(IPAddress.Any, Port);
Object[] State = new Object[] { Client, ListenPt };
Client.BeginReceive(new AsyncCallback(ReceiveCallback), State);
}
public void ReceiveCallback(IAsyncResult ar)
{
UdpClient Client = (UdpClient)((Object[])ar.AsyncState)[0];
IPEndPoint ListenPt = (IPEndPoint)((Object[])ar.AsyncState)[0];
Byte[] receiveBytes = Client.EndReceive(ar, ref ListenPt);
}
EDIT :
the code works will if I give it my local ip and if my clients in my pc .. but if I supply it an external ip it doesn't work ( the exception in the first line comment )
I believe what I am looking to create is a service that listens to a specific port, and when data is sent to that port, it sends off that data to another script for processing.
For some reason though, the service times out when I try to start it. My logs tells me TcpClient client = server.AcceptTcpClient(); is where it is stopping (actually, it is getting stuck on 'starting' in Services).
Since I have no experience with C#, making services, or working with servers in this manner, the code is pretty much just what I found online.
The OnStart method looks like this.
protected override void OnStart(string[] args)
{
try
{
TcpListener server = null;
// Set the TcpListener on port 13000.
Int32 port = 1234;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
// TcpListener server = new TcpListener(port);
server = new TcpListener(localAddr, port);
// Start listening for client requests.
server.Start();
// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;
// Enter the listening loop.
while (true)
{
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
data = null;
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
int i;
// Loop to receive all the data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
// Process the data sent by the client.
data = data.ToUpper();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
// Send back a response.
stream.Write(msg, 0, msg.Length);
}
// Shutdown and end connection
client.Close();
}
}
catch (SocketException e)
{
}
finally
{
}
}
As per MSDN, TcpServer.AcceptTcpClient blocks, so you're probably never returning from your Service's OnStart method, which causes the service to never actually "start".
You might consider using another thread and return from OnStart as soon as possible.
Cheers
As far as creating the Windows service itself, you should be able to use this link, even though it's dated. This companion link shows how to have the service install and uninstall itself. Finally, use this link to understand how to have your service run constantly and how to properly respond to start and stop commands.
To have your service interact with the socket, you'll want to modify the WorkerThreadFunc() from the last link. This is where you should start listening for and processing inbound socket connections.
Im new to Sockets and C# in general and am having a difficult time implementing a simple upd listener function. I've spent alot of time searching the web tying unsuccessfully to intergate any of the numerious examples online. So any suggestions, links, examples would be greatly appreciated!
At this point, I have a third party application broadcasting over port 6600 a general UPD message containing information about the location of the application server (ServerName, IP Address, etc.). I'd like to design my listener client application to capture the UPD broadcast and generate a collection of the available servers which can be used to future processing.
The problem I'm having is that when I attempt to create the listener using listener.Listen(0) if fails and generates a general type error. If I attempt to us the UdpClient class my application hangs and never returns any data. The Code for both examples is listed below:
namespace UDPListener
{
class Program
{
static void Main(string[] args)
{
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
listener.Bind(new IPEndPoint(IPAddress.Any, 6600));
listener.Listen(6);
Socket socket = listener.Accept();
Stream netStream = new NetworkStream(socket);
StreamReader reader = new StreamReader(netStream);
string result = reader.ReadToEnd();
Console.WriteLine(result);
socket.Close();
listener.Close();
}
}
}
And the UdpClient:
private void IdentifyServer()
{
//Creates a UdpClient for reading incoming data.
UdpClient receivingUdpClient = new UdpClient(6600);
//Creates an IPEndPoint to record the IP Address and port number of the sender.
// The IPEndPoint will allow you to read datagrams sent from any source.
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
try
{
// Blocks until a message returns on this socket from a remote host.
Byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);
string returnData = Encoding.ASCII.GetString(receiveBytes);
Output.Text = ("This is the message you received " +
returnData.ToString());
Output.Text = ("This message was sent from " +
RemoteIpEndPoint.Address.ToString() +
" on their port number " +
RemoteIpEndPoint.Port.ToString());
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
dtb was absolutely write! After much research and some help from a friend I realized that what I was actually looking for was a solution for Multicasting. I'll include the links below.
#dtb, thanks for helping point me in the right direction!
http://www.codeproject.com/Articles/1705/IP-Multicasting-in-C
http://codeidol.com/csharp/csharp-network/IP-Multicasting/Csharp-IP-Multicast-Support/
I have asked a couple of similar questions the last couple of days and received some really great help. I now understand my problem quite a bit better but I appear to have hit a snag. I have written a client server application that uses both a TCP and UDP connection. The TCP connection works fine over both LAN and WAN but the UDP connection fails over WAN. Based on the questions I asked previously I realized that my server needed to reply to the client at the EndPoint from which it received a communication. I set everything up to work that way. I will post code after the question. My problem is now that while I am using the EndPoint from the client connection and the client is establishing connection first I am still unable to make the UDP connection. It appeared to work over one network but then failed over all the others I have tried. Any help on figuring this out is appreciated. Here is the code.
Receive UDP Messages on the server
private void receiveUDP()
{
System.Net.IPEndPoint test = new System.Net.IPEndPoint(System.Net.IPAddress.Any,UDP_PORT);
System.Net.EndPoint serverIP = (System.Net.EndPoint)test;
trans.Bind(serverIP);
System.Net.IPEndPoint ipep = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0);
System.Net.EndPoint Remote = (System.Net.EndPoint)ipep;
while (true)
{
byte[] content = new byte[1024];
int recv = trans.ReceiveFrom(content,ref Remote);
int portNum = ((System.Net.IPEndPoint)Remote).Port;
string message = Encoding.ASCII.GetString(content);
string[] data = message.Split((char)124);
//UpdateStatus(data[0] + data[1]);
UserConnection sender = (UserConnection)clients[data[0]];
if (sender.PortNumber != portNum)
sender.PortNumber = portNum;
if (sender.RemoteEnd != Remote)
{
sender.RemoteEnd = Remote;//Stores the EndPoint from the client connection
}
if (data.Length > 2)
{
OnLineRecieved(sender, data[1] + "|" + data[2]);
}
else
{
OnLineRecieved(sender, data[1]);
}
}
}
Client Listens here
private void receiveUDP()
{
System.Net.IPEndPoint test = new System.Net.IPEndPoint(System.Net.IPAddress.Any,UDP_PORT_NUMBER);
System.Net.EndPoint serverIP = (System.Net.EndPoint)test;
server.Bind(serverIP);
server.Ttl = 50;
EndPoint RemoteServ = (EndPoint)servIP;
while (true)
{
byte[] content = new byte[1024];
int data = server.ReceiveFrom(content, ref RemoteServ);
string message = Encoding.ASCII.GetString(content);
result = message;
ProcessCommands(message);
}
}
EDIT: SERVER'S Sending function
public void SendData(string data)
{
if (RemoteEnd != null)//RemoteEnd is refreshed every time the client sends a UDP message
//Each Clients RemoteEnd is stored in a collection of Client objects in a server hashtable
{
//ipep = new IPEndPoint(ipAdd, PortNumber);
byte[] dataArr = Encoding.ASCII.GetBytes(data);
trans.SendTo(dataArr, dataArr.Length, SocketFlags.None, RemoteEnd);
}
}
There could be a lot of things wrong. Remember, UDP doesn't provide transmit pacing, retransmissions, or acknowledgements. So if you need them, you must provide them. If you have the client send first and then wait for responses to each query, your first lost packet will kill the connection.
You also kind of forgot to describe the problem. You say you fail to make the connection, but what does that mean? Does the server receive the client's first packet or not? Does the client receive the server's first reply or not?
You have to determine if this is a programming problem or a network configuration problem.
what I would do is run the client app on the server machine and the server app on the client machine (and switch the hosts they connect to).
If the server app no longer receives UDP messages from the client app, then you have a networking configuration problem.
If the server app can still receive messages from the client app, then you have a programming problem.