IP address conversion to decimal implementation program

Source: Internet
Author: User
Tags explode

, take the IP address of "61.175.232.30" as an example, the IP address is converted to a number string method as follows: First convert "61.175.232.30" to hexadecimal "3d.af.e8.1e", then remove the decimal point and change to "3dafe81e", Finally converts this hexadecimal number to decimal "1034938398", then "61.175.232.30" becomes "1034938398".


Method One:

  code is as follows copy code

Public Function Iptolong () {
        $ ip = $_server[' remote_addr '];
        $ip = Explode ('. ', $IP);
        $ip = Array_reverse ($IP);//array inversion
         $r = 0;
        for ($i =0, $j =count ($IP); $i < $j; $i + +) {
             $r + + $ip [$i] * POW (256, $i);
       }
        $r = sprintf ("%u", $r);
        Echo $r;
}

Method Two:

The code is as follows Copy Code

Public Function Iptolong () {
$ip = $_server[' remote_addr '];
$ip = Explode ('. ', $IP);
$r = ($ip [0] << 24) | ($ip [1] << 16) | ($ip [2] << 8) | $IP [3];
if ($r < 0) $r + = 4294967296;
Echo $r;
}

Tested local IP is: 192.168.1.101, two method conversion result is 3232235877

Ping 192.168.1.101 and ping 3232235877 are the same.


The following provides code for implementing IP address translation in C #:

Code

The code is as follows Copy Code

   //IP Address
       string Ip = "61.175.232.30";
       //Remove IP address remove '. ' The string array
       string [] ip_list = Ip.split ("."). ToCharArray ());
       String x_ip = "";
      //loop array, convert data to hexadecimal number, and merge array (3dafe81e)
        foreach (string IP in ip_list)
       {
                X_ip + = convert.toint16 (Ip). ToString ("X");
      }

      //convert hexadecimal numbers to decimal (1034938398)
       Long N_ip = long. Parse (X_IP, System.Globalization.NumberStyles.HexNumber);

      OK, so the conversion is successful, no, you can test with Windows command-line tools, ping 61.175.232.30 and ping 1034938398 are the same effect, All point to 61.175.232.30.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.