最近在调试程序的时候报SocketException, Message为“请求的名称有效并且在数据库中找到,但是它没有相关的正确的数据来被解析”。此时感到异常疑惑,以为之前一直用Console做测试是没有问题的,但是把代码转移到ActiveX控件就报错了。
原始代码如下
Socket Code 1 private static Socket ConnectSocket(string server, int port)
{
Socket s = null;
IPHostEntry hostEntry = null;
// Get host related information.
hostEntry = Dns.GetHostEntry(server);
// Loop through the AddressList to obtain the supported AddressFamily. This is to avoid
// an exception that occurs when the host IP Address is not compatible with the address family
// (typical in the IPv6 case).
foreach (IPAddress address in hostEntry.AddressList)
{
IPEndPoint ipe = new IPEndPoint(address, port);
Socket tempSocket =
new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
tempSocket.Connect(ipe);
if (tempSocket.Connected)
{
s = tempSocket;
break;
}
else
{
continue;
}
}
return s;
}
在Dns.GetHostEntry(server)时候报错。我怀疑是控件在运行时解析有问题。所以换种方法实现
Socket Code 2 private static Socket ConnectSocket(string server, int port)
{
var bArr = new List<byte>();
foreach(var c in server.Split('.'))
{
bArr.Add(Convert.ToByte(c));
}
IPEndPoint ipe = new IPEndPoint(new IPAddress(bArr.ToArray()), port);
Socket tempSocket =
new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
tempSocket.Connect(ipe);
if (tempSocket.Connected)
{
s = tempSocket;
}
return s;
}
问题解决了