Дипломная работа: Создание сетевой программы DHCP server

Внимание! Если размещение файла нарушает Ваши авторские права, то обязательно сообщите нам

Collection<Class<? extends IFloodlightService>> l = new ArrayList<Class<? extends IFloodlightService>>();

l.add(IFloodlightProviderService.class);

l.add(IDHCPService.class);

l.add(IRestApiService.class);

return l;

}

// private DHCPInstance readDHCPConfig(Map<String, String> configOptions, DHCPInstanceBuilder builder) {

// }

@Override

public void init(FloodlightModuleContext context) throws FloodlightModuleException {

this.floodlightProviderService = context.getServiceImpl(IFloodlightProviderService.class);

this.switchService = context.getServiceImpl(IOFSwitchService.class);

this.restApiService = context.getServiceImpl(IRestApiService.class);

this.topologyService = context.getServiceImpl(ITopologyService.class);

this.staticEntryPusherService = context.getServiceImpl(IStaticEntryPusherService.class);

dhcpInstanceMap = new HashMap<>();

// DHCPInstance instance = readDHCPConfig(context.getConfigParams(this), DHCPInstance.createInstance());

// dhcpInstanceMap.put(instance.getName(), instance);

}

@Override

public void startUp(FloodlightModuleContext context) throws FloodlightModuleException {

floodlightProviderService.addOFMessageListener(OFType.PACKET_IN, this);

switchService.addOFSwitchListener(this);

restApiService.addRestletRoutable(new DHCPServerWebRoutable());

/**

* Thread for DHCP server that periodically check expired DHCP lease

*

* The period of the check for expired lease, in seconds, is specified either in floodlightdefault.properties,

* or through REST API to setup.

*/

leasePoliceDispatcher = new ScheduledThreadPoolExecutor(1);

leasePoliceDispatcher.scheduleAtFixedRate(() -> {

for (DHCPInstance instance : dhcpInstanceMap.values()) {

synchronized (instance.getDHCPPool()) {

instance.getDHCPPool().checkExpiredLeases();

// instance.getDHCPPool().clearExpiredLeases();

}

}

}, 10, DHCP_SERVER_CHECK_EXPIRED_LEASE_PERIOD_SECONDS, TimeUnit.SECONDS);

}

@Override

public void enableDHCP() {

enableDHCPService = true;

}

@Override

public void disableDHCP() {

enableDHCPService = false;

}

@Override

public void enableDHCPDynamic() {

enableDHCPDynamicService = true;

}

@Override

public void disableDHCDynamic() {

enableDHCPDynamicService = false;

}

@Override

public boolean isDHCPDynamicEnabled() {

return enableDHCPDynamicService;

}

@Override

public boolean isDHCPEnabled() {

return enableDHCPService;

}

@Override

public void setCheckExpiredLeasePeriod(long timeSec) {

DHCP_SERVER_CHECK_EXPIRED_LEASE_PERIOD_SECONDS = timeSec;

}

@Override

public Optional<DHCPInstance> getInstance(String name) {

return dhcpInstanceMap.values().stream()

.filter(instance -> instance.getName().contains(name))

.findAny();

}

@Override

public Optional<DHCPInstance> getInstance(IPv4Address ip) {

return dhcpInstanceMap.values().stream()

.filter(dhcpInstance -> dhcpInstance.getDHCPPool().isIPBelongsToPool(ip))

.findAny();

}

@Override

public Optional<DHCPInstance> getInstance(NodePortTuple npt) {

return dhcpInstanceMap.values().stream()

.filter(instance -> instance.getNptMembers().contains(npt))

.findAny();

}

@Override

public Optional<DHCPInstance> getInstance(DatapathId dpid) {

return dhcpInstanceMap.values().stream()

.filter(instance -> instance.getSwitchMembers().contains(dpid))

.findAny();

}

@Override

public Optional<DHCPInstance> getInstance(VlanVid vid) {

return dhcpInstanceMap.values().stream()

.filter(instance -> instance.getVlanMembers().contains(vid))

.findAny();

}

@Override

public Collection<DHCPInstance> getInstances() {

return dhcpInstanceMap.values();

}

@Override

public void addInstance(DHCPInstance instance) {

dhcpInstanceMap.put(instance.getName(), instance);

}

@Override

public boolean deleteInstance(String name) {

if (getInstance(name).isPresent()) {

dhcpInstanceMap.remove(name);

return true;

}

else {

return false;

}

}

@Override

public void deleteAllInstances() {

dhcpInstanceMap.clear();

}

@Override

public DHCPInstance updateInstance(String name, DHCPInstance newInstance) {

DHCPInstance old = dhcpInstanceMap.get(name);

newInstance = old.getBuilder().setSubnetMask(newInstance.getSubnetMask())

.setStartIP(newInstance.getStartIPAddress())

.setEndIP(newInstance.getEndIPAddress())

.setBroadcastIP(newInstance.getBroadcastIP())

.setRouterIP(newInstance.getRouterIP())

.setDomainName(newInstance.getDomainName())

.setLeaseTimeSec(newInstance.getLeaseTimeSec())

.setIPforwarding(newInstance.getIpforwarding())

.setServerMac(newInstance.getServerMac())

.setServerID(newInstance.getServerID())

.build();

return newInstance;

}

@Override

public void switchAdded(DatapathId switchId) { }

@Override

public void switchRemoved(DatapathId switchId) {

dhcpInstanceMap.values().stream()

.forEach(instance -> instance.removeSwitchFromInstance(switchId));

log.info("Handle switchRemoved. Switch {} removed from dhcp instance", switchId.toString());

}

@Override

public void switchActivated(DatapathId switchId) { }

@Override

public void switchPortChanged(DatapathId switchId, OFPortDesc port, PortChangeType type) { }

@Override

public void switchChanged(DatapathId switchId) { }

@Override

public void switchDeactivated(DatapathId switchId) { }

}

У меня есть следующий код

* DHCPServer.java

* DHCPClient.java

* DHCPMessage.java

* DHCPOptions.java

i hav выполнил мою команду promt с помощью javac, у меня нет ошибки, я запускаю код bt, я не знаю, как код работает более конкретно Я не знаю, как запустить его

DHCPServer.java

import java.io.IOException;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.SocketException;import java.util.Arrays;

publicclass DHCPServer {

privatestaticfinalint MAX_BUFFER_SIZE = 1024; // 1024 bytes

privateint listenPort = 67;//1337;

public DHCPServer(int servePort) {

listenPort = servePort;

new DHCPServer();

}

public DHCPServer() {

//System.out.println("Opening UDP Socket On Port: " + listenPort);

DatagramSocket socket = null;

try {

socket = new DatagramSocket(listenPort); // ipaddress? throws socket exception

byte[] payload = newbyte[MAX_BUFFER_SIZE];

int length = 6;

DatagramPacket p = new DatagramPacket(payload, length);

//System.out.println("Success! Now listening on port " + listenPort + "...");

System.out.println("Listening on port " + listenPort + "...");

//server is always listening

boolean listening = true;

while (listening) {

socket.receive(p); //throws i/o exception

System.out.println("Connection established from " + p.getAddress());

System.out.println("Data Received: " + Arrays.toString(p.getData()));

}

} catch (SocketException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

/**

* @param args

*/

publicstaticvoid main(String[] args) {

DHCPServer server;

if (args.length >= 1) {

server = new DHCPServer(Integer.parseInt(args[0]));

} else {

server = new DHCPServer();

}

}

}

DHCPClient.java

Скрыть развернуть код копирования

import java.io.IOException;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;import java.net.NetworkInterface;import java.net.SocketException;import java.net.UnknownHostException;import java.util.Arrays;

publicclass DHCPClient {

privatestaticfinalint MAX_BUFFER_SIZE = 1024; // 1024 bytes

privateint listenPort = 68;//1338;

privateString serverIP = "127.0.0.1";

privateint serverPort = 67;//1337;

/*

* public DHCPClient(int servePort) { listenPort = servePort; new

* DHCPServer(); }

*/

public DHCPClient() {

System.out.println("Connecting to DHCPServer at " + serverIP + " on port " + serverPort + "...");

DatagramSocket socket = null;

try {

socket = new DatagramSocket(listenPort); // ipaddress? throws socket exception

byte[] payload = newbyte[MAX_BUFFER_SIZE];

int length = 6;

payload[0] = 'h';

payload[1] = '3';

payload[2] = 'l';

payload[3] = 'l';

payload[4] = 'o';

payload[5] = '!';

DatagramPacket p = new DatagramPacket(payload, length, InetAddress.getByName(serverIP), serverPort);

socket.send(p); //throws i/o exception

socket.send(p);

System.out.println("Connection Established Successfully!");

System.out.println("Sending data: " + Arrays.toString(p.getData()));

} catch (SocketException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

/**

* @param args

*/

publicstaticvoid main(String[] args) {

DHCPClient client;

/*

* if (args.length >= 1) { server = new

* DHCPClient(Integer.parseInt(args[0])); } else {

*/

client = new DHCPClient();

//DHCPMessage msgTest = new DHCPMessage();

printMacAddress();

// }

}

publicstaticbyte[] getMacAddress() {

byte[] mac = null;

try {

InetAddress address = InetAddress.getLocalHost();

/*

* Get NetworkInterface for the current host and then read the

* hardware address.

*/

NetworkInterface ni = NetworkInterface.getByInetAddress(address);

mac = ni.getHardwareAddress();

} catch (UnknownHostException e) {

e.printStackTrace();

} catch (SocketException e) {

e.printStackTrace();

}

assert(mac != null);

return mac;

}

publicstaticvoid printMacAddress() {

try {

InetAddress address = InetAddress.getLocalHost();

/*

* Get NetworkInterface for the current host and then read the

* hardware address.

*/

NetworkInterface ni = NetworkInterface.getByInetAddress(address);

byte[] mac = ni.getHardwareAddress();

/*

* Extract each array of mac address and convert it to hexa with the

* . * following format 08-00-27-DC-4A-9E.

*/

for (int i = 0; i < mac.length; i++) {

System.out.format("%02X%s", mac[i], (i < mac.length - 1) ? "-"

: "");

}

} catch (UnknownHostException e) {

e.printStackTrace();

} catch (SocketException e) {

e.printStackTrace();

}

}

}

DHCPMessage.java

Скрыть развернуть код копирования

import java.net.Inet4Address;import java.net.InetAddress;

/**

* This class represents a DHCP application level message packet

*/

/**

* @author Laivz

*

*/publicclass DHCPMessage {

privatestaticfinalint BOOTREQUEST = 1;

privatestaticfinalint BOOTREPLY = 2;

privatestaticfinalint DHCPREQUEST = 1;

privatestaticfinalint DHCPREPLY = 2;

privatestaticfinalint ETHERNET10MB = 1;

//Operation Code:

//Specifies the general type of message

privatebyte op;

//Hardware Type:

//Specifies the type of hardware used for the local network

privatebyte hType;

//Hardware Address Length:

//Specifies how long hardware addresses are in this message.

privatebyte hLen;

//Hops:

privatebyte hops;

//Transaction Identifier: (32-bit)

//Identification field generated by client

//private byte[] xid = new byte[3];

privateint xid;

//Seconds: (16-bit)

//Number of seconds elapsed since a client began an attempt to acquire or renew a lease.

//private byte[] secs = new byte[1];

privateshort secs;

//Flags: (16-bit)

//1bit broadcast flag (0-1)

//15 bit reserverd

//private byte[] flags = new byte[1];

privateshort flags;

//Client IP Address: (32-bit)

privatebyte[] cIAddr;

//private InetAddress cIAddr = new Inet4Address();

//"Your" IP Address: (32-bit)

privatebyte[] yIAddr;

//Server IP Address: (32-bit)

privatebyte[] sIAddr;

//Gateway IP Address: (32-bit)

privatebyte[] gIAddr;

//Client Hardware Address: (128-bit : 16 bytes)

privatebyte[] cHAddr;

//Server Name: (512-bit : 64 bytes)

privatebyte[] sName;

//Boot Filename: (1024-bit : 128 bytes)

privatebyte[] file;

//Options: (variable)

private DHCPOptions options;

public DHCPMessage() {

cIAddr = newbyte[4];

yIAddr = newbyte[4];

sIAddr = newbyte[4];

gIAddr = newbyte[4];

cHAddr = newbyte[16];

sName = newbyte[64];

file = newbyte[128];

options = new DHCPOptions();

this.printMessage();

}

publicbyte[] discoverMsg(byte[] cMacAddress) {

op = DHCPREQUEST;

hType = ETHERNET10MB; // (0x1) 10Mb Ethernet

hLen = 6; // (0x6)

hops = 0; // (0x0)

xid = 556223005; // (0x21274A1D)

secs = 0; // (0x0)

flags = 0; // (0x0)

// DHCP: 0............... = No Broadcast

cIAddr = newbyte[] { 0, 0, 0, 0 }; // 0.0.0.0

yIAddr = newbyte[] { 0, 0, 0, 0 }; // 0.0.0.0

sIAddr = newbyte[] { 0, 0, 0, 0 }; // 0.0.0.0

gIAddr = newbyte[] { 0, 0, 0, 0 }; // 0.0.0.0

cHAddr = cMacAddress; // 08002B2ED85E

sName = newbyte[sName.length]; // <Blank>

file = newbyte[file.length]; // <Blank>

// DHCP: Magic Cookie = [OK]

// DHCP: Option Field (options)

// DHCP: DHCP Message Type = DHCP Discover

// DHCP: Client-identifier = (Type: 1) 08 00 2b 2e d8 5e

// DHCP: Host Name = JUMBO-WS

// DHCP: Parameter Request List = (Length: 7) 01 0f 03 2c 2e 2f 06

// DHCP: End of this option field

returnthis.externalize();

}

/**

* Converts a DHCPMessage object to a byte array.

* @return a byte array with information from DHCPMessage object.

*/

publicbyte[] externalize() {

int staticSize = 236;

byte[] options = this.options.externalize();

int size = staticSize + options.length;

byte[] msg = newbyte[size];

//add each field to the msg array

//single bytes

msg[0] = this.op;

msg[1] = this.hType;

msg[2] = this.hLen;

msg[3] = this.hops;

//add multibytes

for (int i=0; i <4; i++) msg[4+i] = inttobytes(xid)[i];

for (int i=0; i <2; i++) msg[8+i] = shorttobytes(secs)[i];

for (int i=0; i <2; i++) msg[10+i] = shorttobytes(flags)[i];

for (int i=0; i <4; i++) msg[12+i] = cIAddr[i];

for (int i=0; i <4; i++) msg[16+i] = yIAddr[i];

for (int i=0; i <4; i++) msg[20+i] = sIAddr[i];

for (int i=0; i <4; i++) msg[24+i] = gIAddr[i];

for (int i=0; i <16; i++) msg[28+i] = cHAddr[i];

for (int i=0; i <64; i++) msg[44+i] = sName[i];

for (int i=0; i <128; i++) msg[108+i] = file[i];

//add options

for (int i=0; i < options.length; i++) msg[staticSize+i] = options[i];

return msg;

}

publicbyte getOp() {

return op;

}

publicvoid setOp(byte op) {

this.op = op;

}

publicbyte getHType() {

return hType;

}

publicvoid setHType(byte type) {

hType = type;

}

publicbyte getHLen() {

return hLen;

}

publicvoid setHLen(byte len) {

hLen = len;

}

publicbyte getHops() {

return hops;

}

publicvoid setHops(byte hops) {

this.hops = hops;

}

publicint getXid() {

return xid;

}

publicvoid setXid(int xid) {

this.xid = xid;

}

publicshort getSecs() {

return secs;

}

publicvoid setSecs(short secs) {

this.secs = secs;

}

publicshort getFlags() {

return flags;

}

publicvoid setFlags(short flags) {

this.flags = flags;

}

publicbyte[] getCIAddr() {

return cIAddr;

}

publicvoid setCIAddr(byte[] addr) {

cIAddr = addr;

}

publicbyte[] getYIAddr() {

return yIAddr;

}

publicvoid setYIAddr(byte[] addr) {

yIAddr = addr;

}

publicbyte[] getSIAddr() {

return sIAddr;

}

publicvoid setSIAddr(byte[] addr) {

sIAddr = addr;

}

publicbyte[] getGIAddr() {

return gIAddr;

}

publicvoid setGIAddr(byte[] addr) {

gIAddr = addr;

}

publicbyte[] getCHAddr() {

return cHAddr;

}

publicvoid setCHAddr(byte[] addr) {

cHAddr = addr;

}

publicbyte[] getSName() {

return sName;

}

publicvoid setSName(byte[] name) {

sName = name;

}

publicbyte[] getFile() {

return file;

}

publicvoid setFile(byte[] file) {

this.file = file;

}

publicbyte[] getOptions() {

return options.externalize();

}

//no set options yet...

/*public void setOptions(byte[] options) {

this.options = options;

}*/

publicvoid printMessage() {

System.out.println(this.toString());

}

@Override

publicString toString() {

String msg = newString();

msg += "Operation Code: " + this.op + "\n";

msg += "Hardware Type: " + this.hType + "\n";

msg += "Hardware Length: " + this.hLen + "\n";

msg += "Hops: " + this.hops + "\n";

msg += Integer.toString(xid) + "\n";

msg += Short.toString(secs) + "\n";

msg += Short.toString(flags) + "\n";

msg += cIAddr.toString() + "\n";

msg += yIAddr.toString() + "\n";

msg += sIAddr.toString() + "\n";

msg += gIAddr.toString() + "\n";

msg += cHAddr.toString() + "\n";

msg += sName.toString() + "\n";

msg += file.toString() + "\n";

msg += options.toString() + "\n";

//add options

assert(file != null);

assert (options != null);

//msg += options.toString();

//return super.toString();

return msg;

}

privatebyte[] inttobytes(int i){

byte[] dword = newbyte[4];

dword[0] = (byte) ((i >>24) & 0x000000FF);

dword[1] = (byte) ((i >>16) & 0x000000FF);

dword[2] = (byte) ((i >>8) & 0x000000FF);

dword[3] = (byte) (i & 0x00FF);

return dword;

}

privatebyte[] shorttobytes(short i){

byte[] b = newbyte[2];

b[0] = (byte) ((i >>8) & 0x000000FF);

b[1] = (byte) (i & 0x00FF);

return b;

}

}

DHCPOptions.java

Скрыть развернуть код копирования

import java.util.Hashtable;import java.util.LinkedList;

/**

* This class represents a hash table of options for a DHCP message.

* Its purpose is to ease option handling such as add, remove, or change.

* @author Laivz

*

*/publicclass DHCPOptions {

//DHCP Message Types

publicstaticfinalint DHCPDISCOVER = 1;

publicstaticfinalint DHCPOFFER = 2;

publicstaticfinalint DHCPREQUEST = 3;

publicstaticfinalint DHCPDECLINE = 4;

publicstaticfinalint DHCPACK = 5;

publicstaticfinalint DHCPNAK = 6;

publicstaticfinalint DHCPRELEASE = 7;

//DHCP Option Identifiers

//private LinkedList<byte[]> options = new LinkedList<byte[]>();

private Hashtable<Integer,byte[]> options;

public DHCPOptions() {

options = new Hashtable<Integer, byte[]>();

}

publicbyte[] getOption(int optionID) {

return options.get(optionID);

}

publicvoid setOption(int optionID, byte[] option) {

options.put(optionID, option);

}

publicbyte[] getOptionData(int optionID) {

byte[] option = options.get(optionID);

byte[] optionData = newbyte[option.length-2];

for (int i=0; i < optionData.length; i++) optionData[i] = option[2+i];

return optionData;

}

publicvoid setOptionData(int optionID, byte[] optionData) {

byte[] option = newbyte[2+optionData.length];

option[0] = (byte) optionID;

option[1] = (byte) optionData.length;

for (int i=0; i < optionData.length; i++) option[2+i] = optionData[i];

options.put(optionID, option);