我在网络适配器上使用以下命令创建IP地址时遇到的问题:
[DllImport("iphlpapi.dll", SetLastError = true)]
private static extern UInt32 AddIPAddress(UInt32 address, UInt32 ipMask, int ifIndex, out IntPtr nteContext, out IntPtr nteInstance);
public void AddIpAddressToInterface(string ipAddress, string subnetMask)
{
var ipAdd = System.Net.IPAddress.Parse(ipAddress);
var subNet = System.Net.IPAddress.Parse(subnetMask);
var nteContext = 0;
var nteInstance = 0;
IntPtr ptrNteContext;
var ptrNteInstance = new IntPtr(nteInstance);
UInt32 result = AddIPAddress((uint)BitConverter.ToInt32(ipAdd.GetAddressBytes(), 0), (uint)BitConverter.ToInt32(subNet.GetAddressBytes(), 0), _adapterIndex, out ptrNteContext,
out ptrNteInstance);
string errorFmt = "Cannot create IP address {0} for adapter {1}. Error: {2}";
if (result == (UInt32)WINERRORS.ERROR_SUCCESS)
{
_ipaddressList.Add(ipAddress, ptrNteContext);
}
else if (result == (UInt32)WINERRORS.ERROR_OBJECT_ALREADY_EXISTS)
{
Logger.LogWarning(string.Format(errorFmt, ipAddress, subNet, (WINERRORS)result));
}
else
{
try
{
Logger.LogError(string.Format(errorFmt, ipAddress, subNet, (WINERRORS)result));
}
catch
{
Logger.LogError(string.Format(errorFmt, ipAddress, subNet, result));
}
}
}
我尝试使用以下方法绑定到IP:注意:LocalPort为0. LocalAddress是使用AddIpAddressToInterface ex创建的。 10.43.55.XXX
var localEndPoint = new IPEndPoint(LocalAddress, LocalPort);
_client = new TcpClient(localEndPoint);
但是我收到了这个错误:
The requested address is not valid in its context
at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress SocketAddress)
at System.Net.Sockets.Socket.Bind(EndPoint localEP)
at System.Net.Sockets.TcpClient..ctor(IPEndPoint localEP)
at CPCToolbox.Shared.TCPConnectionHandler.InitializeNewTCP()
我可以执行ipconfig / all并查看我的IP地址。静态的是10.43.99.199。
路线:
连接呼叫主机是子网255.255.240.0上的远程主机是10.43.99.50端口18000
_client.Connect(_Host, _Port);