src/pkg/net/iprawsock.go - The Go Programming Language

Golang

Source file src/pkg/net/iprawsock.go

     1	// Copyright 2010 The Go Authors.  All rights reserved.
     2	// Use of this source code is governed by a BSD-style
     3	// license that can be found in the LICENSE file.
     4	
     5	// (Raw) IP sockets
     6	
     7	package net
     8	
     9	// IPAddr represents the address of a IP end point.
    10	type IPAddr struct {
    11		IP IP
    12	}
    13	
    14	// Network returns the address's network name, "ip".
    15	func (a *IPAddr) Network() string { return "ip" }
    16	
    17	func (a *IPAddr) String() string {
    18		if a == nil {
    19			return "<nil>"
    20		}
    21		return a.IP.String()
    22	}
    23	
    24	// ResolveIPAddr parses addr as a IP address and resolves domain
    25	// names to numeric addresses on the network net, which must be
    26	// "ip", "ip4" or "ip6".  A literal IPv6 host address must be
    27	// enclosed in square brackets, as in "[::]".
    28	func ResolveIPAddr(net, addr string) (*IPAddr, error) {
    29		ip, err := hostToIP(net, addr)
    30		if err != nil {
    31			return nil, err
    32		}
    33		return &IPAddr{ip}, nil
    34	}
    35	
    36	// Convert "host" into IP address.
    37	func hostToIP(net, host string) (ip IP, err error) {
    38		var addr IP
    39		// Try as an IP address.
    40		addr = ParseIP(host)
    41		if addr == nil {
    42			filter := anyaddr
    43			if net != "" && net[len(net)-1] == '4' {
    44				filter = ipv4only
    45			}
    46			if net != "" && net[len(net)-1] == '6' {
    47				filter = ipv6only
    48			}
    49			// Not an IP address.  Try as a DNS name.
    50			addrs, err1 := LookupHost(host)
    51			if err1 != nil {
    52				err = err1
    53				goto Error
    54			}
    55			addr = firstFavoriteAddr(filter, addrs)
    56			if addr == nil {
    57				// should not happen
    58				err = &AddrError{"LookupHost returned no suitable address", addrs[0]}
    59				goto Error
    60			}
    61		}
    62		return addr, nil
    63	Error:
    64		return nil, err
    65	}