TCP Echo Programming

c0wb3ll ㅣ 2020. 6. 26. 03:44

TCP Echo Programming

TCP_Socket_Server.py

import socket

HOST = "localhost"
PORT = 1337

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

print("binding...")

s.bind((HOST,PORT))

print("Success to bind")

s.listen()
print("Listen...")

c, addr = s.accept()
print("Connected by", addr)

while True:
    data = c.recv(65536)
    if not data:
        break
    print("Received from", addr, data.decode())
    c.sendall(data)

c.close()
s.close()

TCP_Socket_Client

import socket

HOST = '192.168.0.73'
PORT = 8501

c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

c.connect((HOST,PORT))

while True:
    data = input().encode()
    if data == b'exit':
        c.close()
        break
    c.sendall(data)
    data = c.recv(65536)
    print('Received', repr(data.decode()))

Dst, Src Filter Programming

import socket
import struct

def ip_byte_array(name, ip ,ip2, ip3, ip4):
    print(name + ' : ' + str(int(ip.hex(),16)) + '.' + str(int(ip2.hex(),16)) + '.' + str(int(ip3.hex(),16)) + '.' + str(int(ip4.hex(),16)))


def mac_byte_array(name, mac, mac2, mac3, mac4, mac5, mac6):
    print(name + ' : ' + mac.hex() + ':' + mac2.hex() + ':' + mac3.hex() + ':' + mac4.hex() + ':' + mac5.hex() + ':' + mac6.hex())

conn=socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(3))

while True:
    data, addr = conn.recvfrom(65536)
    dst_mac, src_mac, eth_typ = struct.unpack('! 6s 6s H', data[:14])

    if (hex(eth_typ == 0x800)):
        dum0, prot, dum1, src_ip, dst_ip= struct.unpack('! 9s B 2s 4s 4s', data[14:34])


        if (hex(prot == 6)):
            src_port, dst_port = struct.unpack('! H H', data[34:38])

            mac_byte_array("src_mac", src_mac[0:1], src_mac[1:2], src_mac[2:3], src_mac[3:4], src_mac[4:5], src_mac[5:6])
            mac_byte_array("dst_mac", dst_mac[0:1], dst_mac[1:2], dst_mac[2:3], dst_mac[3:4], dst_mac[4:5], dst_mac[5:6])
            ip_byte_array("src_ip", src_ip[0:1], src_ip[1:2], src_ip[2:3], src_ip[3:4])
            ip_byte_array("dst_ip", dst_ip[0:1], dst_ip[1:2], dst_ip[2:3], dst_ip[3:4])
            print("src_port : " + str(src_port))
            print("dst_port : " + str(dst_port))

            print('\n')