I need to check whether a string is a valid IPv4 address in a Windows C++ application. The code I'm using is:
char *ipAddress = ... // get from user input
struct sockaddr_in sa;
int sizeof_sa = sizeof(sa);
int valid = WSAStringToAddressA(ipAddress, AF_INET,NULL, (LPSOCKADDR)&sa,&sizeof_sa);
If I enter "1.2.3" as the value of ipAddress
, WSAStringToAddressA
returns 0, indicating that it is a valid IPv4 address, when it is clearly only three octets.
Why does WSAStringToAddressA
think "1.2.3" is a valid IPv4 address?
Because it is a valid IPv4 address, as far as Microsoft's parsers are concerned. The inet_addr()
documentation explains this in more detail:
Internet Addresses
Values specified using the ".'' notation take one of the following forms:
a.b.c.d a.b.c a.b a
When four parts are specified, each is interpreted as a byte of data and assigned, from left to right, to the 4 bytes of an Internet address. When an Internet address is viewed as a 32-bit integer quantity on the Intel architecture, the bytes referred to above appear as "d.c.b.a''. That is, the bytes on an Intel processor are ordered from right to left.
The parts that make up an address in "." notation can be decimal, octal or hexadecimal as specified in the C language. Numbers that start with "0x" or "0X" imply hexadecimal. Numbers that start with "0" imply octal. All other numbers are interpreted as decimal.
Internet address value Meaning "4.3.2.16" Decimal "004.003.002.020" Octal "0x4.0x3.0x2.0x10" Hexadecimal "4.003.002.0x10" MixThe inet_addr function supports the decimal, octal, hexadecimal, and mixed notations for the string passed in the cp parameter.
Note The following notations are only used by Berkeley software, and nowhere else on the Internet. For compatibility with Berkeley software, the inet_addr function also supports the additional notations specified below.
When a three-part address is specified, the last part is interpreted as a 16-bit quantity and placed in the right-most 2 bytes of the network address. This makes the three-part address format convenient for specifying Class B network addresses as "128.net.host"
When a two-part address is specified, the last part is interpreted as a 24-bit quantity and placed in the right-most 3 bytes of the network address. This makes the two-part address format convenient for specifying Class A network addresses as "net.host''.
When only one part is given, the value is stored directly in the network address without any byte rearrangement.