问题
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.
回答1:
Based on your comment your listening on IPV6. Instead of
ipHostInfo.AddressList[0]
try
ipHostInfo.AddressList.ToList().Find(p=>p.AddressFamily==AddressFamily.InterNetwork);
来源:https://stackoverflow.com/questions/5543718/trouble-getting-sockets-to-connect-in-windows7-64bit