Hey. I've been searching around for a solution to this problem with no luck. I was wondering if this is a known issue when switching socket code from WinXP 32 bit to Win7 64 bit. I have a fairly simple socket routine which works fine in WinXP 32bit, but the socket.connect call is throwing the exception "No connection could be made because the target machine actively refused it 127.0.0.1:48000"
I've added an exception to the win7 firewall for the program, and doubled checked to make sure the rule it added was allowing all ports.
The code I use to setup these simple sockets is as follows:
Listening Socket:
byte[] bytes = new Byte[8192];
IPHostEntry ipHostInfo = Dns.GetHostEntry("localhost");
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 48000);
_ListenerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
_ListenerSocket.Bind(localEndPoint);
_ListenerSocket.Listen(1000);
while (_Running)
{
_ListenerSync.Reset();
_ListenerSocket.BeginAccept(new AsyncCallback(AcceptCallback), _ListenerSocket);
_ListenerSync.WaitOne();
}
_ListenerSocket.Shutdown(SocketShutdown.Both);
_ListenerSocket.Close();
}
Connecting Socket:
IPAddress _IP;
IPAddress.TryParse("127.0.0.1", out _IP)
Socket tTarget = null;
if (tTarget == null)
{
tTarget = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
tTarget.Connect(_IP, 48000);
_Connected = true;
byte[] tBuffer = new byte[8192];
string tRecvBuff = "";
while (_Connected)
{
int tRecv = tTarget.Receive(tBuffer);
//{ does stuff here }
}
Seems like everything works until tTarget.Connect(), where it pauses for a second and then throws the exception listed above. AcceptCallback is never called.
Thanks.
Based on your comment your listening on IPV6. Instead of
ipHostInfo.AddressList[0]
try
ipHostInfo.AddressList.ToList().Find(p=>p.AddressFamily==AddressFamily.InterNetwork);
Related
I use socket communication in a Unity mobile application. The app communicate with different devices. It works 99% of the time, but sometimes the "socket.Connected" part stuck false even, when the device is available (from other instance of the app). So the issue is local. The problem presist even after the app is restarted or even after the phone rebooted! But after some time it works again.
It only stuck with one IP address. (For example with 192.168.1.4 not works, but with 192.168.1.5 works)
So the big question is: What can cause this issue so deep, that even rebooting the phone, does not fix.
static void Thread(object cData)
{
ConnectionData cdata = (ConnectionData)cData;
ConnectAsync(cdata);
}
static void ConnectAsync(ConnectionData cdata)
{
Device device = cdata.device;
string[] messages = cdata.messages;
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
try
{
socket.ReceiveTimeout = timeoutMs;
socket.SendTimeout = timeoutMs;
IPAddress ipAdd = IPAddress.Parse(device.IP);
IPEndPoint remoteEP = new IPEndPoint(ipAdd, device.Port);
IAsyncResult result = socket.BeginConnect(remoteEP, null, null);
result.AsyncWaitHandle.WaitOne(timeoutMs);
if (socket.Connected) // <--THE_PROBLEM = This stuck FALSE
{
...code...
}
}
...
}
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'm trying to write a TCP server in .NETMF 4.3 for my FEZ Spider kit.
public partial class Program
{
void ProgramStarted()
{
ethernetJ11D.NetworkInterface.Open();
ethernetJ11D.UseStaticIP("192.168.0.8", "255.255.255.0", "192.168.0.1");
Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
EndPoint endPoint = new IPEndPoint(IPAddress.Any, 7777);
serverSocket.Bind(endPoint);
serverSocket.Listen(10);
new Thread(() =>
{
while (true)
{
Debug.Print("Network up: " + ethernetJ11D.IsNetworkUp);//true
Debug.Print("Network connected: " + ethernetJ11D.IsNetworkConnected);//true
System.Net.Sockets.Socket clientSocket = serverSocket.Accept();//exception!
new Thread(new Request(clientSocket).Process);
}
}).Start();
}
The serverSocket.Accept method throws a SocketException with error code 10050. This page says it's WSAENETDOWN: Network is down. However the ethernetJ11D's properties state that the connection is up and I can ping the device without any problems. What am I doing wrong?
EDIT
When I tried running the following client I got the same exception on the socket.Connect call.
ethernetJ11D.NetworkInterface.Open();
ethernetJ11D.UseStaticIP("192.168.0.8", "255.255.255.0", "192.168.0.1");
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse("192.168.0.5"), 7777);
socket.Connect(endpoint);
Debug.Print("connected");
byte[] msg = new byte[] { 7, 77, 222 };
socket.Send(msg);
EDIT 2
I've tried to implement the UDP client instead. It doesn't work either.
I've solved the problem:
Change IPAddress.Any to a static IP,e.g. IPAddress.Parse("192.168.0.8").
Delay Bind by adding Thread.Sleep(3000) right before it. It seems that the interface's network settings configuration takes some time.
I am using following piece of code in a program which sends udp multicast packets,
But I get the exception at the very start
static void Main(string[] args)
{
UdpClient udpclient = new UdpClient();
IPAddress multicastaddress = IPAddress.Parse("239.0.0.222");
// Here I get System.Net.Sockets.SocketException , An invalid argument was supplied
udpclient.JoinMulticastGroup(multicastaddress);
...
The mahcine where I have this problem is windows xp. When I run the same code on another machine (windows 7) I do not get this exception, any ideas what could be wrong ?
Thanks
To avoid socket error 10048:
Try:
UdpClient udpclient = new UdpClient();
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, _listenPort);
udpclient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
udpclient.ExclusiveAddressUse = false;
udpclient.Client.Bind(ipEndPoint);
Try to add a port to the udpclient like
udpClient = new udpClient(9000) //or IPEndPoint with IPAddress and Port
anyways dealing with microsofts udpclient is quiet painfully
I have tried to follow the exmaple on the MSDN to create an async server. But nothing seems to be able to connect to it.
http://msdn.microsoft.com/en-us/library/5w7b7x5f.aspx
Here's what I have...
Also notice the AddressList[2], this is not a mistake ;)
private static Socket mListenerSocket;
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPEndPoint localEP = new IPEndPoint(ipHostInfo.AddressList[2], port);
// This line outputs 192.168.0.6:6809 (which is correct)
Console.WriteLine("{0}", localEP.ToString());
mListenerSocket = new Socket(
ipHostInfo.AddressList[2].AddressFamily,
SocketType.Stream,
ProtocolType.Tcp);
mListenerSocket.Bind(localEP);
mListenerSocket.Listen(10);
mListenerSocket.BeginAccept(new AsyncCallback(AcceptCallback), mListenerSocket);
My callback mathod is defined as:
private static void AcceptCallback(IAsyncResult ar)
{
// It does not even get here
mListenerSocket.EndAccept(ar);
}
I would expect when I telnet using 'telnet 192.168.0.6 6809' it should jump to the AcceptCallback method, but it doesn't, so a connection isnt established.
So any ideas why it doesnt work? The are no errors to help me :(
I have tried using a TcpListener instead, but again to still no avail :(
mListenerSocket = new TcpListener(IPAddress.Any, port);
mListenerSocket.Start();
mListenerSocket.BeginAcceptSocket(new AsyncCallback(AcceptCallback), mListenerSocket);
My firewall was preventing connections to the client. Even though I disabled it, I had to restart Visual Studio to capture it.