Reputation: 1764
Was wondering if anyone could help me out here. I don't dont much with c# but its easy for what im trying to do.
I am making a small application that will take in the hostname on my network and then return the full ipaddress(ipv4) ....From there i have options to ping/vnc/telnet...etc.
My question lies here... I am using GetHostEntry
to return the ip address. Then I want to store the IP into a variable, and change the last octet. I figured a simple sting.split('.')
would be the answer, but I can't convert the IP to a string because the source is not a string. Any ideas?
Here is my Method to get the IP address, its just the basic GetHostEntry
method:
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 );
}
Upvotes: 3
Views: 1563
Reputation: 38335
Assuming there is only one network adapter:
// 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 );
Once you have the host IP, you can then use the IP bytes to create a new IP address by modifying any of the octets. In your case, you're wanting the last octect to be modified:
// 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 );
Of course, you can change any of the octets. The above example is only for the 4th octet. If you wanted the first octet, you'd use bytes[0] = 10
.
Upvotes: 1
Reputation: 13419
Here's a rather brittle method that relies on the byte order of your machine and, obviously, the family of the provided address.
byte[] ipBytes = ip.GetAddressBytes();
while (ipBytes[0]++ < byte.MaxValue)
{
var newIp = new IPAddress(ipBytes);
Console.WriteLine(" {0}", ip);
}
Upvotes: 0
Reputation: 22496
You can convert it to a string by using the IPAddress object's ToString() method.
Have you considered just using the System.Net.IPAddress object?
Here is the document on its Parse method, which takes a string and attempts to convert it to an IPAddress object, so you could do whatever string magic you wanted to do: http://msdn.microsoft.com/en-us/library/system.net.ipaddress.parse.aspx
Or, if you want to know how to convert a string to a number, try the numeric data type's TryParse method. Perhaps Int32.TryParse would work.
Upvotes: 0