---
title: "Perl Socket::inet_aton和inet_ntoa"
author: "wtgame"
date: "2011-01-02T20:12:50Z"
tags: []
categories: ["非技术"]
slug: "perl-socket-inet-aton-inet-ntoa"
draft: false
lastmod: "2011-01-03T09:06:00Z"
id: 857710
url: "https://wtgame.iteye.com/blog/857710"
---

得到DNS地址的两个主要函数是Socket模块中的inet\_aton()函数，用来保存DNS地址，然后使用inet\_ntoa()函数把保存的地址转换成IP地址。  
 

l  inet\_aton HOSTNAME

Takes a string giving the name of a host, and translates that to an opaque string (if programming in C, struct in\_addr). Takes arguments of both the 'rtfm.mit.edu' type and '18.181.0.24'. If the host name cannot be resolved, returns undef. For multi-homed hosts (hosts with more than one address), the first address found is returned.

For portability do not assume that the result of inet\_aton() is 32 bits wide, in other words, that it would contain only the IPv4 address in network order.

 

l  inet\_ntoa IP\_ADDRESS

 

Takes a string (an opaque string as returned by inet\_aton(), or a v-string representing the four octets of the IPv4 address in network order) and translates it into a string of the form 'd.d.d.d' where the 'd's are numbers less than 256 (the normal human-readable four dotted number notation for Internet addresses).

 

 

```
#!/usr/bin/perl -w
use strict;
use Socket;

my $ipdotted    = 'www.wtgame.com';
my $ipnetwork   = inet_aton($ipdotted);
my $revipdotted = inet_ntoa($ipnetwork);

print $ipnetwork,"\n";
print "$ipdotted\n$revipdotted \n";
exit 0;
                       
```