Listening to Port 5060 - c#

I developing an SIP client. For this I must listen to port 5060 for incoming SIP Server messages. For this I coded something. (Also I take admin rights in program.)
WindowsPrincipal pricipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
bool hasAdministrativeRight = pricipal.IsInRole(WindowsBuiltInRole.Administrator);
if (hasAdministrativeRight == true)
{
TcpListener server;
Int32 port = 5060;
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... ");
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
data = null;
NetworkStream stream = client.GetStream();
int i;
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);
Console.WriteLine("Sent: {0}", data);
}
client.Close();
}
}
I get SocketException: "An attempt was made to access a socket in a way forbidden by its access permissions" (Native error code: 10013)...
Do you have a suggestion for this?

It seems that you were running two applications, and they are trying
to access the same socket.
What Microsoft says about your problem:
WSAEACCES (10013)
Translation: Permission denied
Description: An attempt was made
to access a socket in a way that is forbidden by its access
permissions. For example, this error occurs when a broadcast address
is used for sendto but the broadcast permission is not set by using
setsockopt(SO_BROADCAST).
Another possible reason for the WSAEACCES
error is that when the bind (Wsapiref_6vzm.asp) function is called (in
Microsoft Windows NT 4 .0 Service Pack 4 [SP4] or later), another
program, service, or kernel mode driver is bound to the same address
with exclusive access. Such exclusive access is a new feature of
Windows NT 4.0 SP4 and later, and it is implemented by using the
SO_EXCLUSIVEADDRUSE option.

Related

Why is my tcp client unable to connect to my server

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.

c# service to listen to a port

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.

error after receiving data over TCP/IP connection using Asynchronous socket communication in c#

i have tried to make TCP/IP connection for a server/client application with asynchronous socket communication and it was successful. However, i am not able to display all the message received by client. i have run time error, may i know where is the problem.
private void onreceive(IAsyncResult ar)
{
Socket clientsocket = (Socket)ar.AsyncState;
int byteread = clientsocket.EndReceive(ar);
data msgreceived = new data(byteData,byteread);
data msgtosend = new data();
byte[] message;
ClientInfo clientinfo = new ClientInfo();
clientinfo.socket = clientsocket;
IPEndPoint remote = clientsocket.RemoteEndPoint as IPEndPoint;
remoteip = remote.Address;
clientinfo.IMEI = msgreceived.IMEI;
clientlist.Add(clientinfo);
msgtosend.strMessage = "client with ip address " + remoteip + " with this IMEI " + clientinfo.IMEI;
txtLog.Text += msgreceived.strMessage + "\r\n";
if (clientinfo.socket.Connected == true)
{
clientsocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(onreceive), clientsocket);
}}
in data class:
public data(byte[] Data, int msglen)
{
//int imeilen = BitConverter.ToInt32(Data, 0);
//int msglen = BitConverter.ToInt32(Data, 4);
//if (imeilen > 0)
// this.IMEI = Encoding.ASCII.GetString(Data, 8, imeilen);
//else this.IMEI = "unknown";
if (msglen > 0)
this.strMessage = Encoding.ASCII.GetString(Data,0, msglen);
else
this.strMessage = "no message";
}
You are somehow magically expecting to know when you have received a "message" despite not even having decided what a message is or writing any code to determine whether one has been received.
There is an old saying in the TCP programming community -- nobody is allowed to write any code that uses TCP until they can 100% explain what every word in this true statement means:
"TCP is a reliable, byte-stream protocol that does not preserve application message boundaries."
You have to code to implement a "message". TCP is a byte-stream protocol. If you want to send and receive messages, you'll need to create a protocol that does that.
Start by defining what a message is, how one is delimited, and so on. Then write code to send and receive messages according to your definition. When your onReceive function is called, that just means the TCP/IP stack received some bytes -- you need to decide whether that's a message or not by following the rules for a the messaging protocol.

Unable to Read byte Stream in C#

I am building a client server application where a client has to send some byte stream and the server responds to it based on the bytes received from the Client. I am using the NetworkStream.Write and NetworkStream.Read methods to send and receive data. The client is able to create a TCP connection to the server. After accepting the connection, the server does NetworkStream.Read and waits for some input from the client. The Client sends the data using the NetworkStream.Write and also does NetworkStream.Flush. But the Server never wakes up from the Read.
Can you guys suggest me what could be the problem here or if you know any other methods to send Byte Stream over a TCP Connection in C# please let me know.
Thanks!
Smart-ass comments aside: even though you are only interested in 2 lines of code, I'm willing to bet your problem is someplace else in your code.
Using a modified version of the code found here, I constructed a simple example that works in my testing.
public static void Main()
{
TcpListener server = null;
try
{
// Set the TcpListener on port 13000.
Int32 port = 13000;
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];
Console.Write("Waiting for a connection... ");
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
stream.Read(bytes, 0, bytes.Length);
Console.WriteLine(System.Text.Encoding.ASCII.GetString(bytes));
// 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();
}
The read call will wait and return when I send it 1 byte with another program. We would need to see some code to figure out why this works and yours does not.

tcp/ip client server not working over internet

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.

Categories

Resources