#!/usr/bin/env python
# Address Family Independent 'Echo client program'
# http://docs.python.org/lib/socket-example.html
# Updated to use AI_ADDRCONFIG which makes
# this program use whatever socket transport is configured
# Please use client code like this from now on

import socket
import sys

HOST = 'mrm-esx-ipv6.eng.vmware.com' # usually dns returns both quad AAAA or A resource records
PORT = 50007          # The same port as used by the server
sck = None
v6Addr = None
afType = None
for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_ADDRCONFIG):
    af, socktype, proto, canonname, sa = res
    try:
	sck = socket.socket(af, socktype, proto)
    except socket.error, msg:
	sck = None
	continue
    try:
	sck.connect(sa)
	v6Addr = sa[0]
	if af == socket.AF_INET6:
           afType = "v6"
        else:
           afType = "v4"
       
    except socket.error, msg:
	sck.close()
	sck = None
        print 'ERROR: connect failed for transport %d, still trying...' % (af)
	continue
    break

if sck is None:
    print 'ERROR: could not connect to server, exiting.'
    sys.exit(1)

print "Sending msg to %s(%s) at port %d" % (HOST, v6Addr, PORT)
sck.send('Hello world over IP%s' % afType)

# older python kits don't define these
try:
    x = socket.SHUT_RD
except AttributeError:
    socket.SHUT_RD = 0
    socket.SHUT_WR = 1
    socket.SHUT_RDWR = 2
    
sck.shutdown(socket.SHUT_WR)
data = sck.recv(1024)
try:
    sck.shutdown(socket.SHUT_RD)
except:  # linux socket.shutdown may throw an error here, freebsd won't
    pass
sck.close()
print 'Received', repr(data)
print "INFO: program complete"
sys.exit(0)
