def client_bgp(threadName, neighbor): while True: cs = socket.socket(socket.AF_INET, socket.SOCK_STREAM) d("Connecting to %s..." % neighbor["ip"]) try: cs.connect((neighbor["ip"], PORT_NUM)) d("Connected to : %s" % neighbor["ip"]) neighbor.update({"socket": cs}) while(True): pkt = MyPacket.encode(KEY_TYPE_REQUEST, thisNet, thisSub, [autoSys], neighbor["linkCost"]) #d("sending:" + ByteToHex(pkt)) cs.send(pkt) time.sleep(INTERVAL) except socket.error, e: print "Socket Error: %s" % str(e) cs.close()
def server_bgp(threadName, conn, addr): while True: #buf = bytearray(BUFFER_SIZE) #recved = conn.recv_into(buf, BUFFER_SIZE) buf = None try: buf = conn.recv(BUFFER_SIZE) except socket.error, e: print "Socket Error: %s" % str(e) #d("Received: %s" % ByteToHex(buf)) recved = 0 if(buf is not None): recved = len(buf) if(recved > 19): (dataType, network, subnet, linkCost, pathVector) = MyPacket.decode(buf) if dataType == KEY_TYPE_REQUEST: neighbor = findNeighborByIp(addr[0]) if neighbor is None: neighbors.append({"ip" : addr[0], "age": AGE_LIFE, "socket": conn}) else: neighbor.update({"age" : AGE_LIFE}) if determineLoop(pathVector): d("Loop detected. Ignoring...") continue print "Received: net:%s sub:%s path:%s" %(network, subnet, pathVector) # Update Routing Table! forward = "" if(pathVector[0] == pathVector[-1]): forward = "Direct" else: forward = "Routed" routingRow = {"network":network, "subnet":subnet, "AS":pathVector[-1], "neighbor": pathVector[0], "linkCost": linkCost, "forward": forward} if(len(routingTable) == 0): routingTable.append(routingRow) else: newcomer = True for route in routingTable: if(route["network"] == network): newcomer = False #Updates the route only if the cost is smaller to make Shortest path! if(route["linkCost"] > linkCost): route["linkCost"] = linkCost route.update(routingRow) d("Link cost is updated with smaller one") if(newcomer): routingTable.append(routingRow) # Finished! Displaying Routing Table displayRoutingTable() #Now we need to add this AS first line and send it to other neighbors #Only floods to the other neighbors if it is set flooding or #the network is not in excluding list!! if(flooding and network not in excluding): pathVector.insert(0, autoSys) for neighbor in neighbors: if(neighbor["ip"] == addr[0]): continue elif "socket" in neighbor: s = neighbor["socket"] pkt = MyPacket.encode(KEY_TYPE_REQUEST, network, subnet, pathVector, linkCost) s.send(pkt) if(recved == 0): break