Is this a bug in IPAddress?
I have recently run across something that appears to be a bug in the IPAddress class. I am including a source example below. In short, the IPAddress class will return a byte array using the GetAddressBytes() method, however, that byte array can not be used in the constructor of another IPAddress object. It looks like IPAddress requires the byte array used in a constructor to be 16 bytes, but the one returned by the GetAddressBytes() method is only 4 bytes.
In addition, another minor bug is that when the class throws an ArgumentException, the Message property is set to the parameter name, and the Parameter property is set to null.
using System;using System.Net;namespace IPAddressBug{ ///<summary> /// Summary description for Class1. ///</summary> class Class1{ ///<summary> /// The main entry point for the application. ///</summary>[STAThread] staticvoid Main(string[] args){ // This works correctly try{ byte[] address =newbyte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x7F };IPAddress ipAddress = new IPAddress( address );} catch ( ArgumentException ex ){ Console.WriteLine( "Unable to create IPAddress from 16-byte byte array" ); Console.WriteLine( "Exception message is {0}, Parameter is {1}", ex.Message, ex.ParamName ); } // This code breaks because the constructor expects a 16-byte array try{ byte[] address =newbyte[] { 0x01, 0x00, 0x00, 0x7F };IPAddress ipAddress = new IPAddress( address );} catch ( ArgumentException ex ){ Console.WriteLine( "Unable to create IPAddress from 4-byte byte array" ); Console.WriteLine( "Exception message is {0}, Parameter is {1}", ex.Message, ex.ParamName ); } // This works correctly try{ IPAddress ipAddress = new IPAddress( 16777343 );} catch ( ArgumentException ex ){ Console.WriteLine( "Unable to create IPAddress from long" ); Console.WriteLine( "Exception message is {0}, Parameter is {1}", ex.Message, ex.ParamName ); } // The following code breaks because the byte[] returned by IPAddress.GetAddressBytes is // 4 bytes long, but the constructor requires a 16-byte array. try{ IPAddress ipAddress = new IPAddress( 16777343 ); byte[] byte_address = ipAddress.GetAddressBytes( );IPAddress ipAddress2 = new IPAddress( byte_address );} catch ( ArgumentException ex ){ Console.WriteLine( "Unable to create IPAddress from byte array returned from IPAddress" ); Console.WriteLine( "Exception message is {0}, Parameter is {1}", ex.Message, ex.ParamName ); } } } } |

