Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.HashMap;
- import java.util.Map;
- public class Arp {
- private int ip;
- private int mac;
- private Map<Integer, Integer> arptable;
- // for simplicity sake the ARP packet format is assumed to be <ip-address>-<mac-address>
- private static final String PACKET_DELIMITER = "-";
- private static final String SPOOF_ALERT_STATUS = "-1";
- private static final String IP_ALREADY_IN_USE_STATUS = "-2";
- private static final String NOT_FOUND = "-3";
- // constructor
- public Arp(int mac, int ip) {
- this.mac = mac;
- this.ip = ip;
- arptable = new HashMap<>();
- arptable.put(ip, mac);
- }
- // This function returns a spoofed ARP packet:
- // The argument passed to this function is the IP address that you want to
- // impersonate.
- public String spoofArp(int spoofIP) {
- return spoofIP + PACKET_DELIMITER + mac;
- }
- // Receive a message and provide the response. This function returns either
- // a packet, or a status code.
- public String receiveArp(String message) {
- String[] tokens = message.split(PACKET_DELIMITER);
- int receivedIp = Integer.parseInt(tokens[0].trim());
- int receivedMac = -1;
- if(tokens.length > 1) {
- receivedMac = Integer.parseInt(tokens[1].trim());
- }
- if(receivedMac == mac && receivedIp != ip) {
- return SPOOF_ALERT_STATUS;
- }
- Integer knownCachedMac = arptable.get(receivedIp);
- if(knownCachedMac != null && receivedMac != -1 && knownCachedMac != receivedMac) {
- return IP_ALREADY_IN_USE_STATUS;
- }
- if(knownCachedMac == null) {
- // cache
- if(receivedMac == -1) {
- message = NOT_FOUND;
- }
- else {
- arptable.put(receivedIp, receivedMac);
- }
- }
- else {
- message = receivedIp + PACKET_DELIMITER + knownCachedMac;
- }
- return message;
- }
- public static void main(String[] args) {
- Arp arp = new Arp(1, 1);
- String spoofPacket = arp.spoofArp(2);
- if(!spoofPacket.equals("2-1")) {
- System.out.println("Improper spoofing, expected 2-1 but received " + spoofPacket);
- }
- String receivedMessage = arp.receiveArp("6-1");
- if(!receivedMessage.equals(SPOOF_ALERT_STATUS)) {
- System.out.println("expected a spoofing alert but didn't arrive");
- }
- receivedMessage = arp.receiveArp("2-2");
- if(!receivedMessage.equals("2-2")) {
- System.out.println("expected the same message to be returned");
- }
- receivedMessage = arp.receiveArp("2-");
- if(!receivedMessage.equals("2-2")) {
- System.out.println("expected cached message to be returned");
- }
- receivedMessage = arp.receiveArp("2-5");
- if(!receivedMessage.equals(IP_ALREADY_IN_USE_STATUS)) {
- System.out.println("expected IP_ALREADY_IN_USE_STATUS");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement