想知道是否有人可以帮助我。我对 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 地址。在您的情况下,您希望修改最后一个八位字节:
// 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
。
关于c# - 更改 gethostentry 返回的 IP 的最后八位字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7589772/