System.Net.IPAddress returning weird addresses

别等时光非礼了梦想. 提交于 2021-02-10 03:52:38

问题


I am writing a (rather simple :) networking application, and am testing it using localhost:27488 (127.0.0.1:27488).
I am using a System.Net.Sockets.TcpClient for the connection, which takes a System.Net.IPAddress to specify the host... the only thing is, I can't figure out how to initialize the class with the right IP address. I went over the MSDN docs and it says it takes either a Byte(4) or an Int64 (long) for the address.
The probelm is, when I initialize the IPAddress like this:

Dim ipAddr As New System.Net.IPAddress(127001)

it returns the address as 25.240.1.0. From what I understand from the docs, 127001 should return 127.0.0.1... Maybe I missed something there? http://msdn.microsoft.com/en-us/library/13180abx.aspx


回答1:


Short answer: use TcpClient.Connect( String, Int ) instead; it accepts an IPv4/IPv6 address or hostname/alias, so you are not limited to connecting by IP. e.g.:

Dim client As TcpClient
client.Connect( "localhost", 27488 )
client.Connect( "127.0.0.1", 27488 )

But where did 25.240.1.0 come from? Try the following:

  • Open Calc, switch to Programmer view, select Dec
  • Type in 127001, then switch to Hex
  • Write out the result, adding zeroes on the left to pad to 4 bytes/32 bits: 0001F019
  • Separate that number into individual bytes: 00 01 F0 19
  • Reverse the byte order: 19 F0 01 00
  • Convert each byte back to decimal: 25 240 1 0
  • With dots: 25.240.1.0

Why reverse the bytes? Your processor architecture is little-endian; numbers are represented in memory with the least significant byte first. IPv4 addresses are standardized to big-endian format (most significant byte first; a.k.a. network order). The IPAddress( Int64 ) constructor is reversing the bytes to convert from LE to BE.

Reversing the steps above, the correct value for loopback in the IPAddress( Int64 ) constructor would be &H0100007F (hex) or 16777343 (decimal).

The IPAddress( Byte[4] ) constructor takes the byte array in network order, so that would be New Byte() { 127, 0, 0, 1 }




回答2:


You are misunderstating how it works. Ip address consists of 4 bytes, representing them as 127.0.0.1 is just a human readable convention. Under the hood, 127.0.0.1 is represented as ((127 << 24) | (0 << 16) | (0 << 8) | 1). In your case, it would be much easier and more readable to just use .Parse(string) method like this:

IPAddress.Parse("127.0.0.1");




回答3:


Why not try the IPAddress.Parse method?

You'd do something like:

Dim ipAddr as IPAddress = IPAddress.Parse("127.0.0.1")


来源:https://stackoverflow.com/questions/6929487/system-net-ipaddress-returning-weird-addresses

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!