Canot create udp connection on mono - c#

I can not create a UDP connection:
public void Connect(String host, int port)
{
System.Net.IPAddress address = Dns.GetHostAddresses (host)[0];
this.hostport = new IPEndPoint(address, port);
this.socket = new Socket(
AddressFamily.InterNetwork,
SocketType.Dgram,
ProtocolType.Udp
);
this.socket.BeginConnect(this.hostport, new AsyncCallback(socket__onConnect), this.socket);
}
private void socket__onConnect(IAsyncResult ar)
{
// It is never called on udp connections :(
try
{
Socket client = (Socket) ar.AsyncState;
client.EndConnect(ar);
Console.WriteLine("Success!");
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
Try connect but socket__onConnect is never called.
With TCP works fine but UDP doeas not works.
I have perrmissions to connect udp port:
nc -v -u host.com 53
Works fine.

Mono bug? try this:
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp) { ExclusiveAddressUse = true ; } ;

Related

Connecting to C# socket through public IP address

Good evening everyone,
I'm having trouble connecting to a Socket using my IP address. I can connect by using my local address, but no luck getting it to work with my public one.
If I go on www.canyouseeme.org I can see that my server receives the connection and the site says it can see the service.
Here is the code. Client
public void Connect() {
IPAddress ipAddr = IPAddress.Parse("xx.xx.143.138");
clientSocket = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
// Connect
clientSocket.Connect(new IPEndPoint(ipAddr, 7777));
}
Server:
private void Listen() {
IPAddress ipAddr = IPAddress.Any;
serverSocket = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(new IPEndPoint(ipAddr, 7777));
}
Thanks in advance,
Emiliano

C# Socket works locally but not remotely

I have a C# Client and a seperate Server application. When i execute both on the same machine, im able to connect to the server. However, when i try to connect to my server remotely it always ends in a timeout. I use the port 139 and I tried running the server application on mulitple machines. I have tried it on a server that is open to the public, my private PC with my router forwarding this port to the PC, as well as laptops in the same network.
I have always checked if the machine the server is running on is listening on the port using netstat -an and made exceptions in the firewall on all of them.
The code I use on the client to connect to the server:
static IPHostEntry ipHostInfo = Dns.GetHostEntry("xxx.xxx.xxx.xxx");
static IPAddress ipAddress = ipHostInfo.AddressList[0];
static IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
static Socket client = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
static private void ConnectToServer()
{
try
{
client.BeginConnect(remoteEP,
new AsyncCallback(ConnectCallback), client);
connectDone.WaitOne();
}
catch (Exception ex)
{
Console.WriteLine("Error: ", ex.ToString());
}
}
private static void ConnectCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket client = (Socket)ar.AsyncState;
// Complete the connection.
client.EndConnect(ar);
Console.WriteLine("Socket connected to {0}",
client.RemoteEndPoint.ToString());
// Signal that the connection has been made.
connectDone.Set();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
The code I use to accept the connection on the server:
static IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
static IPAddress ipAddress = ipHostInfo.AddressList[0];
static IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 139);
static Socket listener = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
try
{
listener.Bind(localEndPoint);
listener.Listen(100);
while (true)
{
allDone.Reset();
Console.WriteLine("Listening on: " + ipAddress);
listener.BeginAccept(
new AsyncCallback(AcceptCallback),
listener);
allDone.WaitOne();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
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);
}
As I said this works flawlessly when both client and server application are executed on the same PC. If however they are on different machines the client gets a timout error within a couple of seconds.
Any help is appreciated, Thanks.

Socket not connecting with IPEndPoint

I have a System.Net.Sockets.Socket connecting to a back end.
public class Connection
{
private readonly Socket _client;
private readonly IPEndPoint _endPoint;
byte[] _sendBuf = new byte[0x1000];
protected Connection(string host, int port)
{
var ipAddress = IPAddress.Parse(host);
_endPoint = new IPEndPoint(ipAddress, port);
_client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
protected void Connect()
{
//Fails
_client.Connect(_endPoint);
}
}
The socket tries to connect but timeouts when Connect function is called. But if I provide host and port parameters to Socket.Connect function instead of an IPEndPoint with those, it connects successfully.
protected void Connect()
{
//Connects
_client.Connect(host, port); //same as used in creating IPEndPoint above
}
Why? The end point I'm trying to connect is in a VPN with the network I'm in.

How to get IP address with a host name?

I am making a client that connect to a server that is locally hosted that gets stock numbers from the server. The program does work if i use this code below but the way it works is by getting the dns name so in theory it only takes www.website.com and I cant figure out how I can get it to recognize a normal ip of 127.0.0.1 or localhost IP:
IPHostEntry ipHostInfo = Dns.GetHostEntry("www.website.com");
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
Attached is my attemp to get this to resolve the ip but I dont think I am approaching this right the full code can be seen here:StockReader Client Code
public class AsynchronousClient
{
private const int port = 21;
// ManualResetEvent instances signal completion.
private static ManualResetEvent connectDone =
new ManualResetEvent(false);
private static ManualResetEvent sendDone =
new ManualResetEvent(false);
private static ManualResetEvent receiveDone =
new ManualResetEvent(false);
// The response from the remote device.
private static String response = String.Empty;
private static void StartClient()
{
// Connect to a remote device.
try
{
// Establish the remote endpoint for the socket.
// The name of the
//******************ISSUE BEGINS HERE*********************************
string sHostName = Dns.GetHostName();
IPHostEntry ipHostInfo = Dns.GetHostEntry(sHostName);
IPAddress [] ipAddress = ipHostInfo.AddressList;
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
// Create a TCP/IP socket.
Socket client = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Connect to the remote endpoint.
client.BeginConnect(remoteEP,
new AsyncCallback(ConnectCallback), client);
connectDone.WaitOne();
// Send test data to the remote device.
Send(client, "This is a test<EOF>");
sendDone.WaitOne();
// Receive the response from the remote device.
Receive(client);
receiveDone.WaitOne();
// Write the response to the console.
Console.WriteLine("Response received : {0}", response);
// Release the socket.
client.Shutdown(SocketShutdown.Both);
client.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
When you set the value of ipAddress, you can use the IPAddress.Parse method to pass in a string and retrieve an IPAddress object instead of using the domain name:
string ip = "127.0.0.1";
IPAddress address = IPAddress.Parse(ipAddress);
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
Try using string sHostName = "localhost";
// Establish the remote endpoint for the socket.
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
IPEndPoint remoteEP = new IPEndPoint(ipAddress, portnumber);
// Create a TCP/IP socket.
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
s.Connect(remoteEP);

How can I test a TCP connection to a server with C# given the server's IP address and port?

How can I programmatically determine if I have access to a server (TCP) with a given IP address and port using C#?
You could use the Ping class (.NET 2.0 and above)
Ping x = new Ping();
PingReply reply = x.Send(IPAddress.Parse("127.0.0.1"));
if(reply.Status == IPStatus.Success)
Console.WriteLine("Address is accessible");
You might want to use the asynchronous methods in a production system to allow cancelling, etc.
Assuming you mean through a TCP socket:
IPAddress IP;
if(IPAddress.TryParse("127.0.0.1",out IP)){
Socket s = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
try{
s.Connect(IPs[0], port);
}
catch(Exception ex){
// something went wrong
}
}
For more information: http://msdn.microsoft.com/en-us/library/4xzx2d41.aspx?ppud=4
Declare string address and int port and you are ready to connect through the TcpClient class.
System.Net.Sockets.TcpClient client = new TcpClient();
try
{
client.Connect(address, port);
Console.WriteLine("Connection open, host active");
} catch (SocketException ex)
{
Console.WriteLine("Connection could not be established due to: \n" + ex.Message);
}
finally
{
client.Close();
}
This should do it
bool ssl;
ssl = false;
int maxWaitMillisec;
maxWaitMillisec = 20000;
int port = 555;
success = socket.Connect("Your ip address",port,ssl,maxWaitMillisec);
if (success != true) {
MessageBox.Show(socket.LastErrorText);
return;
}

Categories

Resources