Question

In: Computer Science

For each of below python socket functions, describe network traffic (resulting TCP packets) that is generated...

For each of below python socket functions, describe network traffic (resulting TCP packets) that is generated at the TCP level. Note: s represents an open socket.
Python network APIs Resulting TCP packets
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 8080))
s.send('ABC'.encode('utf-8'))
data = s.recv(2000)
s.shutdown(socket.SHUT_WR)

Solutions

Expert Solution

import socket

# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Bind the socket to the port
server_address = ('localhost', 10000)
print('Starting up on {} port {}'.format(*server_address))
sock.bind(server_address)

# Listen for incoming connections
sock.listen(1)

while True:
    # Wait for a connection
    print('waiting for a connection')
    connection, client_address = sock.accept()
    try:
        print('connection from', client_address)

        # Receive the data in small chunks and retransmit it
        while True:
            data = connection.recv(16)
            print('received {!r}'.format(data))
            if data:
                print('sending data back to the client')
                connection.sendall(data)
            else:
                print('no data from', client_address)
                break

    finally:
        # Clean up the connection
        print("Closing current connection")
        connection.close()
# create an INET, STREAMing socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# now connect to the web server on port 80 - the normal http port
s.connect(("www.python.org", 80))
# create an INET, STREAMing socket
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# bind the socket to a public host, and a well-known port
serversocket.bind((socket.gethostname(), 80))
# become a server socket
serversocket.listen(5)
import socket
import time
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 8088))
s.listen(10)
while 1:
    c, addr = s.accept()
    print c, addr
    c.send('hello')
    c.close()
s.shutdown()
and

import socket 
s = socket.socket()
s.connect(('127.0.0.1', 8080))
while 1:
    print s.recv(2048)
# Set up the variables we'll use
>>> uni_greeting = u'Hi, my name is %s.'
>>> utf8_greeting = uni_greeting.encode('utf-8')

>>> uni_name = u'José'  # Note the accented e.
>>> utf8_name = uni_name.encode('utf-8')

# Plugging a Unicode into another Unicode works fine
>>> uni_greeting % uni_name
u'Hi, my name is Josxe9.'

# Plugging UTF-8 into another UTF-8 string works too
>>> utf8_greeting % utf8_name
'Hi, my name is Josxc3xa9.'

# You can plug Unicode into a UTF-8 byte sequence...
>>> utf8_greeting % uni_name  # UTF-8 invisibly decoded into Unicode; note the return type
u'Hi, my name is Josxe9.'

# But plugging a UTF-8 string into a Unicode doesn't work so well...
>>> uni_greeting % utf8_name  # Invisible decoding doesn't work in this direction.
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 3: ordinal not in range(128)

# Unless you plug in ASCII-compatible data, that is.
>>> uni_greeting % u'Bob'.encode('utf-8')
u'Hi, my name is Bob.'

# And you can forget about string interpolation completely if you're using UTF-16.
>>> uni_greeting.encode('utf-16') % uni_name
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
ValueError: unsupported format character '' (0x0) at index 33
import socket, sys
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

HOST = '127.0.0.1'
PORT = 1060

if sys.argv[1:] == ['server']:
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind((HOST, PORT))
    s.listen(1)
    while True:
        print 'Listening at', s.getsockname()
        sc, sockname = s.accept()
        print 'Processing up to 1024 bytes at a time from', sockname
        n = 0
        while True:
            message = sc.recv(1024)
            if not message:
                break
            sc.sendall(message.upper())  # send it back uppercase
            n += len(message)
            print '\r%d bytes processed so far' % (n,),
            sys.stdout.flush()
        print
        sc.close()
        print 'Completed processing'

elif len(sys.argv) == 3 and sys.argv[1] == 'client' and sys.argv[2].isdigit():

    bytes = (int(sys.argv[2]) + 15) // 16 * 16  # round up to // 16
    message = 'capitalize this!'  # 16-byte message to repeat over and over

    print 'Sending', bytes, 'bytes of data, in chunks of 16 bytes'
    s.connect((HOST, PORT))

    sent = 0
    while sent < bytes:
        s.sendall(message)
        sent += len(message)
        print '\r%d bytes sent' % (sent,),
        sys.stdout.flush()

    print
    s.shutdown(socket.SHUT_WR)

    print 'Receiving all the data the server sends back'

    received = 0
    while True:
        data = s.recv(42)
        if not received:
            print 'The first data received says', repr(data)
        received += len(data)
        if not data:
            break
        print '\r%d bytes received' % (received,),

    s.close()

else:
    print >>sys.stderr, 'usage: tcp_deadlock.py server | client <bytes>'

Related Solutions

write a skeleton Python TCP servers as follows: Multi-threaded concurrent TCP server using Python’s low-level socket...
write a skeleton Python TCP servers as follows: Multi-threaded concurrent TCP server using Python’s low-level socket module and Python’s threading library Python sockets API: s = socket(), s.bind(), s.listen(), remote_socket, remote_addr = s.accept() Python threading API: thread = threading.Thread(target, args, daemon), thread.start()
Analyzing network traffic and understanding packets is an important task for IT security professionals. Illegitimate hackers...
Analyzing network traffic and understanding packets is an important task for IT security professionals. Illegitimate hackers also use network traffic to steal information and/or to about an organization's network infrastructure. How can different methods of packet capture be useful and why might one be chosen over another? How can understanding of the OSI model inform a discussion of packet capture?
1. Consider running real-time traffic, like VoIP, over a TCP or UDP socket. Why might you...
1. Consider running real-time traffic, like VoIP, over a TCP or UDP socket. Why might you prefer to run such an application using a UDP transport layer? 2. Consider running real-time traffic, like VoIP, over a TCP or UDP socket. Suppose you chose to use TCP for your application; what would you need to do to ensure that the robust transport algorithm does not harm real-time performance?
Python 3 Forming Functions Define and complete the functions described below. * function name: say_hi *...
Python 3 Forming Functions Define and complete the functions described below. * function name: say_hi * parameters: none * returns: N/A * operation: just say "hi" when called. * expected output: >>> say_hi() hi * function name: personal_hi * parameters: name (string) * returns: N/A * operation: Similar to say_hi, but you should include the name argument in the greeting. * expected output: >>> personal_hi("Samantha") Hi, Samantha * function name: introduce * parameters: name1 (string) name2 (string) * returns: N/A...
Python 3 Functions that give answers Define and complete the functions described below. * function name:...
Python 3 Functions that give answers Define and complete the functions described below. * function name: get_name * parameters: none * returns: string * operation: Here, I just want you to return YOUR name. * expected output: JUST RETURNS THE NAME...TO VIEW IT YOU CAN PRINT IT AS BELOW >>> print(get_name()) John * function name: get_full_name * parameters: fname (string) lname (string) first_last (boolean) * returns: string * operation: Return (again, NOT print) the full name based on the first...
PYTHON: Write a script that imports the functions in the module below and uses all of...
PYTHON: Write a script that imports the functions in the module below and uses all of the functions. import math def _main():     print("#" * 28, "\n", "Testing...1, 2, 3...testing!\n", "#" * 28, "\n", sep="")     f = -200     print("{:.2f} F is {:.2f} C".format(f, f2c(f)))     f = 125     print("{:.2f} F is {:.2f} C".format(f, f2c(f)))     c = 0     print("{:.2f} C is {:.2f} F".format(c, c2f(c)))     c = -200     print("{:.2f} C is {:.2f} F".format(c, c2f(c))) def f2c(temp):     #Converts Fahrenheit tempature to Celcius     if temp <...
Please write python code for the following. Implement the functions defined below. Include a triple-quoted comments...
Please write python code for the following. Implement the functions defined below. Include a triple-quoted comments string at the bottom displaying your output. Using sets (described in Deitel chapter 6) will simplify your work. Below is the starter template for the code: def overlap(user1, user2, interests): """ Return the number of interests that user1 and user2 have in common """ return 0    def most_similar(user, interests): """ Determine the name of user who is most similar to the input user...
Describe each of the following economic functions of money and provide an example of each: (1)...
Describe each of the following economic functions of money and provide an example of each: (1) medium of exchange; (2) standard of value; and (3) store of value.
PYTHON Computer Science Objectives Work with lists Work with functions Work with files Assignment Write each...
PYTHON Computer Science Objectives Work with lists Work with functions Work with files Assignment Write each of the following functions. The function header must be implemented exactly as specified. Write a main function that tests each of your functions. Specifics In the main function ask for a filename and fill a list with the values from the file. Each file should have one numeric value per line. This has been done numerous times in class. You can create the data...
5 Briefly describe the functions of the parts of the brain listed in the table below.
5 Briefly describe the functions of the parts of the brain listed in the table below.6 List the parts some of the cranial nerves innervate and the functions they control:What would happen if Vagus (NX) nerve is cut?Which of the above listed nerves are sensory only?Which of the above listed nerves are mixed nerves?
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT