更改gethostentry返回的IP的最后八位
本文关键字:最后 八位 IP 更改 返回 gethostentry | 更新日期: 2023-09-27 18:09:54
不知道有没有人能帮我一下。我不太懂c#,但它很容易做我想做的事情。
我正在制作一个小应用程序,它将在我的网络上接受主机名,然后返回完整的ipaddress(ipv4) ....从那里我有选项ping/vnc/telnet…等。
我的问题是……我使用GetHostEntry
返回ip地址。然后我要将IP存储到一个变量中,并更改最后八位字节。我想一个简单的sting.split('.')
将是答案,但我不能将IP转换为字符串,因为源不是字符串。什么好主意吗?这是我的方法来获得IP地址,它只是基本的GetHostEntry
方法:
IPHostEntry host = Dns.GetHostEntry( hostname );
Console.WriteLine( "GetHostEntry({0}) returns: {1}", hostname, host );
// This will loop though the IPAddress system array and echo out
// the results to the console window
foreach ( IPAddress ip in host.AddressList )
{
Console.WriteLine( " {0}", ip );
}
假设只有一个网络适配器:
// When an empty string is passed as the host name,
// GetHostEntry method returns the IPv4 addresses of the local host
// alternatively, could use: Dns.GetHostEntry( Dns.GetHostName() )
IPHostEntry entries = Dns.GetHostEntry( string.Empty );
// find the local ipv4 address
IPAddress hostIp = entries.AddressList
.Single( x => x.AddressFamily == AddressFamily.InterNetwork );
一旦你有了主机IP,你就可以使用IP字节通过修改任意八位元组来创建一个新的IP地址。在您的示例中,您希望修改最后一个oct:
// grab the bytes from the host IP
var bytes = hostIp.GetAddressBytes();
// set the 4th octect (change 10 to whatever the 4th octect should be)
bytes[3] = 10;
// create a new IP address
var newIp = new IPAddress( bytes );
当然,您可以更改任何八位元组。上面的例子只适用于第4个八位。如果需要第一个八位字节,则使用bytes[0] = 10
。
这是一个相当脆弱的方法,它依赖于您的机器的字节顺序,显然,还依赖于所提供的地址族。
byte[] ipBytes = ip.GetAddressBytes();
while (ipBytes[0]++ < byte.MaxValue)
{
var newIp = new IPAddress(ipBytes);
Console.WriteLine(" {0}", ip);
}
可以使用IPAddress对象的ToString()方法将其转换为字符串。
你考虑过仅仅使用System.Net.IPAddress对象吗?
下面是Parse方法的文档,该方法接受一个字符串并尝试将其转换为IPAddress对象,因此您可以执行任何想要执行的字符串魔术:http://msdn.microsoft.com/en-us/library/system.net.ipaddress.parse.aspx
或者,如果您想知道如何将字符串转换为数字,请尝试数字数据类型的TryParse方法。也许Int32。