I have server application .
If I run it at server application just do not communicate with client. I try allow all ports used ports in firewall also whole application, but it did not helped. At localhost it works fine. Working system is correctly updated Win 10. Server is windows server 2012.
public void Listen(object data)
{
// Establish the local endpoint for the socket.
// The DNS name of the computer
// running the listener is "host.contoso.com".
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket listener = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(100);
while (true)
{
// Set the event to nonsignaled state.
allDone.Reset();
// Start an asynchronous socket to listen for connections.
Console.WriteLine("Waiting for a connection...at" + localEndPoint.ToString());
listener.BeginAccept(
new AsyncCallback(AcceptCallback),
listener);
// Wait until a connection is made before continuing.
allDone.WaitOne();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
Seems you should be using IPv4 Adresses.
You can use IPAdress's AdressFamily property to get a to valid IPv4 Address ("InterNetwork"). Also check isLoopback().
So, basically
IPAdress myIp = ipHostInfo
.AddressList
.Where( a => a.AddressFamily == AddressFamily.InterNetwork)
.FirstOrDefault(x => !IPAdress.IsLoopback(x));
should give you a good one if one exists.
... or as Damien_The_Unbeliever so greatly reminded me in comment:
Just use IPAdress.Any to listen on any ip.
Related
I'm writing a very simple .NET TCP Server and very simple TCP Client that should both run on the same machine (Window 10 Home PC) and connect each other (for testing purposes only).
In the server I'm waiting for the connection in this way:
public static void StartListening()
{
string hostname = Dns.GetHostName();
IPHostEntry ipHostInfo = Dns.GetHostEntry(hostname);
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, Properties.Settings.Default.Port);
Socket listener = new Socket(
ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
try
{
listener.Bind(localEndPoint);
listener.Listen(Properties.Settings.Default.Port);
while (true)
{
allDone.Reset();
Console.WriteLine("Waiting for a connection...");
listener.BeginAccept(
new AsyncCallback(AcceptCallback),
listener);
allDone.WaitOne();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
public static void AcceptCallback(IAsyncResult ar)
{
allDone.Set();
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
var frames = Directory.EnumerateFiles(Properties.Settings.Default.FramesPath);
foreach (string filename in frames)
{
Console.Write("Sending frame: {}...", filename);
SendFile(handler, filename);
Thread.Sleep(Properties.Settings.Default.FrameDelay);
}
}
In the client I'm creating a connection in this way:
private void startClient(string host, int port)
{
IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse(host), port);
ClientTCP = new TcpClient();
ClientTCP.Connect(serverEndPoint);
Reader = new StreamReader(ClientTCP.GetStream());
Listen = true;
listner = Listener();
}
startClient is called in this way.
startClient(txtAddr.Text, (int)int.Parse(txtPort.Text));
When I run the client setting host variable to the current machine name (the same the server retrieve trough Dns.GetHostName() I got this exception:
An invalid ip address was specified.
I tried using 127.0.0.1 and I got:
Connection could not be established. Persistent rejection of the target computer 127.0.0.1:5002
I tried with localhost and I got
An invalid ip address was specified
again. I tried with the IP address assigned to WiFi and I got again
Connection could not be established. Persistent rejection of the target computer 192.168.10.11:5002
I'm sure the computer network works since I'm using it for many other things including connecting to local TCP services and I'm sure both client and server code works since on a different PC I'm able to connect them setting localhost as client host variable value. Why I'm unable to use loopback connections in my code?
Where did I fail?
P.S. I allowed connection to server binary in Windows firewall rules, I also allowed outgoing connection for client binary also.
For anyone willing to inspect the server code here it is:
Server code
You are using the constructor with the "IPEndPoint" parameter. This constructor does not connect to the server automatically and you must call the "Connect" method before using the socket. That is why you are getting the error message "Operation not allowed on unconnected sockets". Also, you have provided a wrong IPEndPoint for client.
Please try this on client:
private void startClient(string host, int port)
{
IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse(host), port);
ClientTCP = new TcpClient();
ClientTCP.Connect(serverEndPoint);
Reader = new StreamReader(ClientTCP.GetStream());
Listen = true;
listner = Listener();
}
You may need some exception handling here, but it should work now.
UPDATE:
The ipHostInfo.AddressList may have more than one addresses and just one of them is what you wanted. It is not necessarily the first one. I specified this manually and it works:
//string hostname = Dns.GetHostName();
//IPHostEntry ipHostInfo = Dns.GetHostEntry("127.0.0.1");
//IPAddress ipAddress = ipHostInfo.AddressList[0];
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 5002);
I am working on an ATM project (tcp/ip, C#). I have to click the start button in server application to start listening client. OInce client sends sign on request (connect), connection between server and client is established (up to this part I am done).
When sign of request comes from the client, I have to disconnect the connection and start listen for client again. The code for listening client is as below.
public bool startlisten()
{
byte[] buffer = new byte[4000];
try
{
//Creates one SocketPermission object for access restrictions
permission = new SocketPermission(
NetworkAccess.Accept, // Allowed to accept connections
TransportType.Tcp, // Defines transport types
"", // The IP addresses of local host
SocketPermission.AllPorts // Specifies all ports
);
// Listening Socket object
sListener = null;
//Ensures the code to have permission to access a Socket
permission.Demand();
// Resolves a host name to an IPHostEntry instance
IPHostEntry ipHost = Dns.GetHostEntry("");
int portnumber = int.Parse(ConfigurationManager.AppSettings.Get("port"));
// Creates a network endpoint
ipEndPoint = new IPEndPoint(IPAddress.Any, portnumber);
// Create one Socket object to listen the incoming connection
sListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Associates a Socket with a local endpoint
sListener.Bind(ipEndPoint);
// Places a Socket in a listening state and specifies the maximum
// Length of the pending connections queue
sListener.Listen(10);
//Begins an asynchronous operation to accept an attempt
AsyncCallback aCallback = new AsyncCallback(AcceptCallback);
sListener.BeginAccept(aCallback, sListener);
}
catch (Exception exc) {
return true;
}
return true;
}
Please guide me how to disconnect from client socket and start listening again.
i have tried
//handler.Disconnect(false);
//handler.Shutdown(SocketShutdown.Both);
//handler.Close();
sListener and handler are the Socket object.while accepting (acceptconnection) listener is copied to handler.
I am using this server example from MSND: http://msdn.microsoft.com/en-us/library/fx6588te.aspx
and from some reason my server refuse to connect at this function at _listener.Bind(localEndPoint); with error Only one usage of each socket address (protocol/network address/port) is normally permitted
Until a few minutes ago I had no problems Sarver connect without problems and suddenly it happens
public static void StartListening(IPAddress ipAddress, int port)
{
_isServerRunning = true;
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
// The DNS name of the computer
// running the listener is "host.contoso.com".
//IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
//IPAddress ipAddress = IPAddress.Parse("192.168.0.100"); //ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port);
// Create a TCP/IP socket.
_listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and listen for incoming connections.
try
{
_listener.Bind(localEndPoint);
_listener.Listen(100);
while (true)
{
// Set the event to nonsignaled state.
allDone.Reset();
// Start an asynchronous socket to listen for connections.
Console.WriteLine("Waiting for a connection...");
_listener.BeginAccept(
new AsyncCallback(AcceptCallback),
_listener);
// Wait until a connection is made before continuing.
allDone.WaitOne();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
//Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
What does this error means ?
It most likely means that the local port is still reserved. This can be idther because another process is still runnoing and holding the sockewt open, or because the timeout period defined by th dSO_LINGER socket option is not timed out. I'm not familiar with c# but there should be a way to set th elinger timeout.
You can tell the current status of the socket by using the netstat command.
I think you can find some solutions here http://blogs.msdn.com/b/dgorti/archive/2005/09/18/470766.aspx
I have a system monitor app that needs to listen to messages from various UDP sockets on another machine. The other sockets continuously send heartbeats to this given IP/port.
This exception gets thrown when calling BeginReceiveFrom:
"A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied"
I shouldn't have to call connect because data is already getting sent to this ip endpoint. plus the data is coming from various sockets.
private Socket m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
private void Window_Loaded(object sender, RoutedEventArgs e)
{
// bind socket
// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
m_localEndPoint = new IPEndPoint(ipAddress, 19018);
m_socket.Bind(m_localEndPoint);
m_socket.BeginReceiveFrom(m_data,
m_nBytes,
MAX_READ_SIZE,
SocketFlags.None,
ref m_localEndPoint,
new AsyncCallback(OnReceive),
null);
}
private void OnReceive(IAsyncResult ar)
{
int nRead = m_socket.EndReceiveFrom(ar, ref m_localEndPoint);
}
I was able to get the desired behavior with the UdpClient class.
Your problem was you were binding to the IP assigned to you, you should bind to IP you want receive from - in your case:
m_socket.Bind(new IPEndPoint(IPAddress.Any, 12345));
This is related to c# Sockets.
I'm developping a socket program. But there is one problem in my software.
I cannot connect to computers which are connected to internet via theirs local network. But I can connect to computers that are uses internet alone. Be more descriptive,
Consider that 5 computers connects internet via a modem that uses 1 ip address. When I try to reach one of these computers, API connects to modem via its ip address. But there is no response. Because a modem don't respond a computer request. By the mean, my API must reach a computer not only modem. And and an SocketException is thrown. What can I do about this problem?
The problem you're encountering is caused by NAT. This is used by routers who allow multiple clients to go online through one public IP address. None of the clients behind the router will 'know' or 'see' this, but it limits connectivity.
Clients can initiate a connection to the outside, but the other way around is basically* impossible. Unless you use port forwarding, where one or more ports are forwarded to a client behind the router. This way, connections can be initiated from the outside.
This requires configuration on the client side however, so the preferred way would be to let your clients connect to your server, since that will always be possible (firewalls neglected).
*: There also is a workaround, where you let a client connect to your server, and then pass the connection information to another client, so those clients can communicate with each other. This is called 'nat punching' and is used by torrent clients, for example.
you can try something like this.....
server Side Code
namespace Consoleserver
{
class Program
{
static void Main(string[] args)
{
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp );
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
while (true)
{
Console.WriteLine("Waiting for a connection...");
Socket handler = listener.Accept();
Console.WriteLine("connected");
}
}
catch { Console.WriteLine("error");
}
}
}
Client side code :
namespace consoleclient
{
class Program
{
static void Main(string[] args)
{
try
{
IPHostEntry ipHostInfo = Dns.Resolve("59.178.131.180");
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);
Socket sender = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
try
{
sender.Connect(remoteEP);
Console.WriteLine("Socket connected <strong class="highlight">to</strong> {0}",
sender.RemoteEndPoint.ToString());
}
catch (ArgumentNullException ane)
{
Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
Console.Read();
}
catch (SocketException se)
{
Console.WriteLine("SocketException : {0}", se.ToString());
Console.Read();
}
catch (Exception e)
{
Console.WriteLine("Unexpected exception : {0}", e.ToString());
Console.Read();
}
}
catch
{ Console.WriteLine("could not <strong class="highlight">connect</strong> A"); }
}
}
}
I hope it will helps you