Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

c# - ip address increment problem

I want to increase my ip address and;

Here is the code

 ipAddressControl1.Text = "192.168.1.255";

 byte[] ip = ipAddressControl1.GetAddressBytes();
 ip[3] = (byte)(++ip[3]);

 IPAddress ipAddress1 = new IPAddress(ip);
 MessageBox.Show(ipAddress1.ToString());

or I also tried this

ipAddressControl3.Text = "192.168.1.255";
 IPAddress ipAddress1 = new IPAddress(?pAddressControl3.GetAddressBytes());
 ipAddress1.Address += 0x1 << 24;
 MessageBox.Show(ipAddress1.ToString());

but both of them gives me 192.168.1.0 but I want to get value as 192.168.2.0

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your problem is that you're not increasing ip[2] when ip[3] wraps around (and so on up the hierarchy). The following code should do the trick, finally wrapping from 255.255.255.255 to 0.0.0.0:

byte[] ip = ipAddressControl1.GetAddressBytes();
ip[3] = (byte)(ip[3] + 1);
if (ip[3] == 0) {
    ip[2] = (byte)(ip[2] + 1);
    if (ip[2] == 0) {
        ip[1] = (byte)(ip[1] + 1);
        if (ip[1] == 0) {
            ip[0] = (byte)(ip[0] + 1);
        }
    }
}

The following may also work:

byte[] ip = ipAddressControl1.GetAddressBytes();
if (++ip[3] == 0)
    if (++ip[2] == 0)
        if (++ip[1] == 0)
            ++ip[0];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...